如何使用 SAX Java 解析器读取注释文本

Fas*_*ast 4 java xml parsing sax

我只想使用 Java 中的 SAX 解析器读取 XML 文件中对象标记的注释。

\n\n

这是我的文件的摘要:

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

Fer*_*ntl 6

javax.xml.parsers.SAXParser支持阅读评论。它忽略了它们。

允许您在使用org.xml.sax.XMLReaderorg.xml.sax.ext.LexicalHandler进行解析时捕获注释。请参阅另一篇 stackoverflow 帖子中的示例或Oracle 中的教程

如果您想将注释连接到紧随其后的元素,您还可以将 a 传递org.xml.sax.ContentHandler给解析器并通过它跟踪其他 XML 内容。我修改了上面提到的代码以仅打印该object元素,该元素前面紧接着有一条注释:

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());
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

将此代码保存到“Test.java”,并将 XML 内容保存到“test.xml”。编译并执行后,它应该给出以下输出:

$ javac Test.java 
$ java Test 
Element object with comment found: "Object Seed term: day, WikiTitle: day"
Run Code Online (Sandbox Code Playgroud)