2017-01-08 1 views
1

Java의 SAX 파서를 사용해 XML 파일의 오브젝트 태그에 대해서만 코멘트를 읽고 싶다.SAX Java 파서로 코멘트 텍스트를 읽는 법

<!-- Object Seed term: day, WikiTitle: day--> 
<object id="15155220" name="solar day, twenty-four hour period, 24-hour interval, mean solar day, twenty-four hours, si day, día, days, si days, day duration, day, civil day"> 
    <!-- class: "calendar day" --> 
    <class id="15157041" name="calendar day, civil day"></class> 
    <!-- class: "unit of time" --> 
    <class id="15154774" name="time units, unit of time, time unit, units of time"></class> 
    <!-- class: "" --> 
    <class id="15113229" name="period of time, time period, period"></class> 
    <!-- class: "" --> 
    <class id="00000000" name="time"></class> 
    <genericPhysicalDescription> 
     <!-- hasPart: "" --> 
     <hasPart id="15228378" name="hour, time of day"></hasPart> 
     <!-- hasPart: "" --> 
     <hasPart id="15157225" name="day"></hasPart> 
     <!-- partOf: "calendar" --> 
     <partOf id="15173479" name="calendrics, calendar, dating style, calendarist, calendars, birthday calendar, calendar strip, secular calendar, calandar, agriculture calendar, calendar system, criminal calendar"></partOf> 
     <!-- partOf: "" --> 
     <partOf id="15206296" name="month"></partOf> 
     <!-- partOf: "" --> 
     <partOf id="15157225" name="day"></partOf> 
    </genericPhysicalDescription> 
</object> 
+0

그래, 내 응용 프로그램이 SAX 파서 참고하시기 바랍니다 – Fast

+0

에 기반을, 색소폰 다소 .. –

답변

0

javax.xml.parsers.SAXParser 댓글을 읽는 지원하지 않습니다

내 파일의 추상적이다. 그것들은 무시합니다.

org.xml.sax.ext.LexicalHandlerorg.xml.sax.XMLReader으로 구문 분석 할 때 주석을 잡을 수 있습니다. 예 : another stackoverflow post 또는 tutorial at Oracle을 참조하십시오.

바로 뒤에 오는 요소에 주석을 연결하려면 org.xml.sax.ContentHandler을 파서에 전달하고 다른 XML 내용을 추적 할 수 있습니다.

import org.xml.sax.*; 
import org.xml.sax.ext.*; 
import org.xml.sax.helpers.*; 

import java.io.IOException; 

public class Test implements LexicalHandler, ContentHandler { 

    private String lastComment; 

    public void startDTD(String name, String publicId, String systemId) throws SAXException { 
    } 
    public void endDTD() throws SAXException { 
    } 
    public void startEntity(String name) throws SAXException { 
    } 
    public void endEntity(String name) throws SAXException { 
    } 
    public void startCDATA() throws SAXException { 
    } 
    public void endCDATA() throws SAXException { 
    } 
    public void comment(char[] text, int start, int length) throws SAXException { 
    this.lastComment = new String(text, start, length).trim(); 
    } 

    public void characters(char[] ch, int start, int length) { 
    } 
    public void endDocument() { 
    } 
    public void endElement(String uri, String localName, String qName) { 
    } 
    public void endPrefixMapping(String prefix) { 
    } 
    public void ignorableWhitespace(char[] ch, int start, int length) { 
    } 
    public void processingInstruction(String target, String data) { 
    } 
    public void setDocumentLocator(Locator locator) { 
    } 
    public void skippedEntity(String name) { 
    } 
    public void startDocument() { 
    } 
    public void startElement(String uri, String localName, String qName, Attributes atts) { 
    if (localName == "object") { 
     if (this.lastComment != null) { 
     System.out.println("Element object with comment found: \"" + this.lastComment + "\""); 
     this.lastComment = null; 
     } 
    } else { 
     this.lastComment = null; 
    } 
    } 
    public void startPrefixMapping(String prefix, String uri) { 
    } 

    public static void main(String[] args) { 
    Test test = new Test(); 
    XMLReader parser; 

    try { 
     parser = XMLReaderFactory.createXMLReader(); 
    } catch (SAXException ex1) { 
     try { 
     parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); 
     } catch (SAXException ex2) { 
     return; 
     } 
    } 

    try { 
     parser.setProperty("http://xml.org/sax/properties/lexical-handler", test); 
    } catch (SAXNotRecognizedException e) { 
     System.out.println(e.getMessage()); 
     return; 
    } catch (SAXNotSupportedException e) { 
     System.out.println(e.getMessage()); 
     return; 
    } 

    parser.setContentHandler(test); 

    try { 
     parser.parse("test.xml"); 
    } catch (SAXParseException e) { 
     System.out.println(e.getMessage()); 
    } catch (SAXException e) { 
     System.out.println(e.getMessage()); 
    } catch (IOException e) { 
     System.out.println(e.getMessage()); 
    } 
    } 
} 

저장이 코드를 "Test.java"및 "test.xml의"당신의 XML 내용 : 난 단지 그 object 즉시 코멘트가 선행 요소를 인쇄하려면 위의 언급 된 코드를 적응. 일단 컴파일 및 실행, 그것은 당신에게 다음과 같은 출력을 제공한다 :

$ javac Test.java 
$ java Test 
Element object with comment found: "Object Seed term: day, WikiTitle: day" 
+0

이 코드 때 시작 읽기 XML을 구문 분석의 오래된 및 구식 방법입니다 모든 주석 e가 파싱을 수행 한 후 – Fast

+0

사실,'LexicalHandler'는 요소를 추적하지 않습니다; 'ContentHandler'도 파서에 설정해야합니다. 추가 XML 내용을 추적하고 주석과 요소를 함께 연결할 수 있어야합니다. 나는'object' 엘리먼트에 대한 주석만을 출력하도록 내 대답을 업데이트했습니다. –

+0

감사합니다. 작동합니다! – Fast