2013-12-10 2 views
1

사이트에서 HTML 코드를 파싱하면 거의 완료됩니다. 나는 사이트에서 필요한 텍스트 부분을 가지고 있지만 때때로 HTMl에 포함되어있는 일부 링크가 제거되기를 원합니다. 나는 내가 원하지 않는 요소들이 모두 '<'그리고 물론 '>'로 시작한다는 사실을 생각하고있다. 이 작업을 수행 할 여지가 있습니까? 이것은 내가 지금까지 가지고있는 것이다.문자열에서 세그먼트 제거

for(int i = 0; i<desc.length();i++) 
    { 
     if(desc.charAt(i)==('<')){ 

     } 
    } 

desc 내 문자열을 잘라 내고 싶습니다.

답변

0

일반적으로 XML 및 HTML과 같은 마크 업 언어를 수동으로 구문 분석하는 것은 좋지 않습니다. 그러나 모든 요소를 ​​제거하려고하는 경우 간단한 스크립트가 어디에 유용 할 수 있는지 확인할 수 있습니다.

내가 언급 할만한 가치가 있다고 생각되는 것은 HTML의 모든 요소를 ​​제거하면 여러 텍스트가 함께 걸릴 수 있다는 것입니다. 이 코드를보고 도움이되는지 확인하십시오.

public class RemoveHtmlElements { 

    public static void main(String[] args) { 

     String html = "<!DOCTYPE html><html><body><h1>My First Heading</h1>" 
       + "<p>My first paragraph.</p></body></html>"; 

     boolean elementsExist = true; 
     while(elementsExist) { 
      if(html.contains("<")) { 
       int open = html.indexOf("<"); 
       int closed = html.indexOf(">", open); 
       html = html.substring(0, open) + " " + html.substring(closed + 1); 
      } else { 
       elementsExist = false; 
      } 
     } 

     System.out.println(html); 

    } 

} 

괄호로 묶인 요소의 HTML을 정리해야합니다. 예기치 않게 텍스트가 함께 걸리지 않도록 요소를 제거하는 공간을 입력합니다.

0

나는 이것을 다음과 같이 시도 할 것이다.

StringBuilder sb = new StringBuilder(); 
boolean open = false; 
for (char c : desc.toCharArray()) { // iterate over the characters 
    if (c == '<') { // if we hit a less then store that the tag is open. 
    open = true; 
    } else if (open && c == '>') { // if the tag is open and the close symbol hits close. 
    open = false; 
    } else if (!open) { // if the tag isn't open 
    sb.append(c); 
    } 
} 
System.out.println(sb.toString()); // print the string.