2012-03-04 5 views
0

У меня есть назначение лаборатории, и я остановился на том, чтобы удалить html-теги. Вот способ удаления HTML-теги:удаление оставшихся html-тегов

public String getFilteredPageContents() { 
    String str = getUnfilteredPageContents(); 
    String temp = ""; 
    boolean b = false; 
    for(int i = 0; i<str.length(); i++) { 
     if(str.charAt(i) == '&' || str.charAt(i) == '<') { 
      b = true; 
     } 
     if(b == false) { 
      temp += str.charAt(i); 
     } 
     if(str.charAt(i) == '>' || str.charAt(i) == ';') { 
      b = false; 
     } 
    } 
    return temp; 
} 

А вот ранняя форма моего текста:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> 
<html> 

<head> 
<meta http-equiv="Content-Type" 
content="text/html; charset=iso-8859-1"> 
<meta name="GENERATOR" content="Microsoft FrontPage 2.0"> 
<title>A Shropshire Lad</title> 
</head> 

<body bgcolor="#008000" text="#FFFFFF" topmargin="10" 
leftmargin="20"> 

<p align="center"><font size="6"><strong></strong></font>&nbsp;</p> 
<div align="center"><center> 

<pre><font size="7"><strong>A Shropshire Lad 
</strong></font><strong> 
by A.E. Housman 
Published by Dover 1990</strong></pre> 
</center></div> 

<p><strong>This collection of sixty three poems appeared in 1896. 
Many of them make references to Shrewsbury and Shropshire, 
however, Housman was not a native of the county. The Shropshire 
of his book is a mindscape in which he blends old ballad meters, 
classical reminiscences and intense emotional experiences 
&quot;recollected in tranquility.&quot; Although they are not 
particularly to my taste, their style, simplicity and 
timelessness are obvious even to me. Below are two short poems 
which amused me, I hope you find them interesting too.</strong></p> 

<hr size="8" width="80%" color="#FFFFFF"> 
<div align="left"> 

<pre><font size="5"><strong><u> 
XIII</u></strong></font><font size="4"><strong> 

When I was one-and-twenty 
I heard a wise man say, 
'Give crowns and pounds and guineas 
But not your heart away;</strong></font></pre> 
</div><div align="left"> 

<pre><font size="4"><strong>Give pearls away and rubies 
But keep your fancy free. 
But I was one-and-twenty, 
No use to talk to me.</strong></font></pre> 
</div><div align="left"> 

<pre><font size="4"><strong>When I was one-and-twenty 
I heard him say again, 
'The heart out of the bosom 
Was never given in vain; 
'Tis paid with sighs a plenty 
And sold for endless rue' 
And I am two-and-twenty, 
And oh, 'tis true 'tis true. 

</strong></font><strong></strong></pre> 
</div> 

<hr size="8" width="80%" color="#FFFFFF"> 

<pre><font size="5"><strong><u>LVI . The Day of Battle</u></strong></font><font 
size="4"><strong> 

'Far I hear the bugle blow 
To call me where I would not go, 
And the guns begin the song, 
&quot;Soldier, fly or stay for long.&quot;</strong></font></pre> 

<pre><font size="4"><strong>'Comrade, if to turn and fly 
Made a soldier never die, 
Fly I would, for who would not? 
'Tis sure no pleasure to be shot.</strong></font></pre> 

<pre><font size="4"><strong>'But since the man that runs away 
Lives to die another day, 
And cowards' funerals, when they come, 
Are not wept so well at home,</strong></font></pre> 

<pre><font size="4"><strong>'Therefore, though the best is bad, 
Stand and do the best, my lad; 
Stand and fight and see your slain, 
And take the bullet in your brain.'</strong></font></pre> 

<hr size="8" width="80%" color="#FFFFFF"> 
</body> 
</html> 

И когда реализовать мой метод по этому тексту:

charset=iso-8859-1"> 

A Shropshire Lad 







A Shropshire Lad 

by A.E. Housman 
Published by Dover 1990 


This collection of sixty three poems appeared in 1896. 
Many of them make references to Shrewsbury and Shropshire, 
however, Housman was not a native of the county. The Shropshire 
of his book is a mindscape in which he blends old ballad meters, 
classical reminiscences and intense emotional experiences 
recollected in tranquility. Although they are not 
particularly to my taste, their style, simplicity and 
timelessness are obvious even to me. Below are two short poems 
which amused me, I hope you find them interesting too. 
. 
. 
. 

Мой вопрос: Как я могу избавиться от этого небольшого кода в самом начале текста charset=iso-8859-1">. Я не могу уйти от этой кучи кода? Спасибо ...

+0

вы можете начать использовать его, избегая использования главной страницы. такие инструменты могут быть удобны в обмен на правильный код – Joseph

+0

Избегайте FrontPage, вероятно, хорошая идея. Но я думал, что задание состоит в обработке HTML-кода, независимо от того, откуда он может произойти? – Nayuki

ответ

2

Я вижу, что вы намерены удалить вещи, которые выглядят как <xxx> и &xxx;. Вы используете переменную b, чтобы помнить, пропускаете ли вы в данный момент материал или нет.

Вы заметили, что ваш алгоритм пропустит все формы <xxx; и &xxx>? А именно, & или < вызовет пропуск, чтобы начать, и > или ; вызовет пропуск до конца, но вы не должны совпадать < с > или & с ;. Итак, как насчет реализации кода, чтобы запомнить, какой символ начал пропустить?

Еще одна сложность, однако, заключается в том, что &xxx; материал может быть встроен в <xxx> вещи, как это: <p title="&amp;">

Кстати, temp += str.charAt(i); сделает вашу программу очень медленно, когда строка долго. Посмотрите на использование StringBuilder.


Вот код, который должен решить вашу проблему или почти так:

import java.util.Stack; 

public String getFilteredPageContents() { 
    String str = getUnfilteredPageContents(); 
    StringBuilder() temp = new StringBuilder(); 

    // The closing character for each thing that we're inside 
    Stack<Character> expectedClosing = new Stack<Character>(); 

    for(int i = 0; i<str.length(); i++) { 
     char c = str.charAt(i); 
     if(c == '<') 
      expectedClosing.push('>'); 
     else if(c == '&') 
      expectedClosing.push(';'); 

     // Is the current character going to close something? 
     else if(!expectedClosing.empty() && c == expectedClosing.peek()) 
      expectedClosing.pop(); 

     else { 
      // Only add to output if not currently inside something 
      if(expectedClosing.empty()) 
       temp.append(c); 
     } 
    } 
    return temp.toString(); 
} 
0

Это присвоение школе, но и любой шанс, что вы могли бы использовать хорошо сформированный HTML-парсер, такие как this для работы ?

+0

Я не могу использовать внешние библиотеки или парсеры для этого назначения. – El3ctr0n1c4

0

Самый элегантный способ решения этого сценария, вероятно, будет использовать regular expressions. С ними вы могли бы специально искать структуры тегов и удалять их из вывода.

Однако, поскольку вы уже закодировали программу, и она отлично работает, за исключением проблемы, о которой вы упомянули, может возникнуть достаточно грязное решение &.

Единственное, что я могу придумать, это применить фильтр-подобный алгоритм, который сканирует вывод текста по строкам и удаляет их, если они присутствуют. Как чтение каждой строки и проверка, является ли последний символ >. Если он удаляет строку/заменяет ее пустой строкой. В обычном тексте не должно быть > и в конце предложения, поэтому у вас не должно быть слишком много проблем.

Смежные вопросы