我有一个像这样的xml:
<Message xmlns="uri_of_message">
<VendorId>1234</VendorId>
<SequenceNumber>1</SequenceNumber>
...other important headers...
<Data>
<Functions xmlns="uri_of_functions_subxml">
<Function1 attr="sth">
<Info>Some_Info</Info>
</Function1>
<Function2>
<Info>Some_Info</Info>
</Function2>
...Functions n...
</Functions>
</Data>
</Message>
我需要提取内部xml
<Functions xmlns="uri_of_functions_subxml">
<Function1 attr="sth">
<Info>Some_Info</Info>
</Function1>
<Function2>
<Info>Some_Info</Info>
</Function2>
...Functions n...
</Functions>
我首先尝试使用字符方法获取内部xml:
public void startElement(String uri, String localName, String tagName, Attributes attributes) throws SAXException {
if (tagName.equalsIgnoreCase("Data")){
buffer = new StringBuffer();}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (buffer != null) {
buffer.append(new String(ch, start, length).trim());
}
}
public void endElement(String uri, String localName, String tagName) throws SAXException {
if (tagName.equalsIgnoreCase("Data")){
innerXML = buffer.toString().trim();
}
但后来我意识到字符方法没有正确收集xml,它可能会拒绝像“&lt;”,“&gt;”这样的特殊字符。
下面的链接包含相同的问题,但答案不适用于我,因为外部xml必须作为握手信号处理,内部xml必须以完全不同的方式处理。
Java XML parsing: taking inner XML using SAX
我唯一需要的是正确收集内部xml。但是,怎么做呢? 提前谢谢..
答案 0 :(得分:4)
SAX似乎不是这项工作的最佳选择,无论如何尝试
SAXParser p = SAXParserFactory.newInstance().newSAXParser();
XMLReader filter = new XMLFilterImpl(p.getXMLReader()) {
private boolean inFunctions;
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (!inFunctions && qName.equals("Functions")) {
inFunctions = true;
}
if (inFunctions) {
super.startElement(uri, localName, qName, atts);
} else {
qName.equals("Functions");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (inFunctions) {
super.endElement(uri, localName, qName);
if (qName.equals("Functions")) {
inFunctions = false;
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (inFunctions) {
super.characters(ch, start, length);
}
}
};
Transformer t = TransformerFactory.newInstance().newTransformer();
Source source = new SAXSource(filter, new InputSource(new FileInputStream("1.xml")));
Result result = new StreamResult(System.out);
t.transform(source, result);
}
输出
<?xml version="1.0" encoding="UTF-8"?><Functions xmlns="uri_of_functions_subxml">
<Function1 attr="sth">
<Info>Some_Info</Info>
</Function1>
<Function2>
<Info>Some_Info</Info>
</Function2>
</Functions>