有没有办法在使用XStream with Java解析它时读取xml注释。
<!--
Mesh: three-dimensional box 100m x 50m x 50m Created By Sumit Purohit on
for a stackoverflow query.
-->
<ParameterList name="Mesh">
<Parameter name="Domain Low Corner" type="Array double" value="{0.0, 0.0, 0.0}" />
<Parameter name="Domain High Corner" type="Array double" value="{100.0, 50.0,50.0}" />
</ParameterList>
我目前使用XStream来序列化/反序列化上面的那种xml。我需要在我的POJO上将注释保存为注释,以便我可以在UI中显示它。
我在XStream中找不到任何东西。
DOM有DocumentBuilderFactory.setIgnoringComments(boolean),允许您在DOM树中包含注释,并且可以区分节点类型。
答案 0 :(得分:1)
尝试使用LexicalHandler API从XML解析CData和Comments。
答案 1 :(得分:1)
根据我的知识,XStream无法处理XML注释。
这是另一种使用LexicalHandler API的方法:
import org.xml.sax.*;
import org.xml.sax.ext.*;
import org.xml.sax.helpers.*;
import java.io.IOException;
public class ReadXMLFile implements LexicalHandler {
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 {
System.out.println("Comment: " + new String(text, start, length));
}
public static void main(String[] args) {
// set up the parser
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",new ReadXMLFile()
);
} catch (SAXNotRecognizedException e) {
System.out.println(e.getMessage());
return;
} catch (SAXNotSupportedException e) {
System.out.println(e.getMessage());
return;
}
try {
parser.parse("xmlfile.xml"); // <---- Path to XML file
} catch (SAXParseException e) { // well-formedness error
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
}
}
}