【发布时间】:2021-09-29 15:33:56
【问题描述】:
您好,我正在尝试使用 SAX 解析 xml 文件并根据元素值对其进行过滤并将结果保存在另一个文件中。
XML 文件示例:
<ruleset>
<rule>
<condition>
<case1>String testing</case1>
<allow>true</allow>
</condition>
</rule>
<rule>
<condition>
<case2>String test</case2>
<allow>false</allow>
</condition>
</rule>
</ruleset>
我希望结果文件如下
<ruleset>
<rule>
<condition>
<case2>String test</case2>
<allow>false</allow>
</condition>
</rule>
</ruleset>
由于标签的值为“false”,所以我主要想根据元素的值过滤循环元素
到目前为止的代码帮助我根据父元素而不是元素过滤所有元素。
final String splitElement = "Rule";
XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
private boolean skip;
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts)
throws SAXException {
if (qName.equals(splitElement)) {
super.startElement(uri, localName, qName, atts);
skip = false;
} else {
if (!skip) {
super.startElement(uri, localName, qName, atts);
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (!skip) {
super.endElement(uri, localName, qName);
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (!skip) {
super.characters(ch, start, length);
}
}
};
Source src = new SAXSource(xr, new InputSource(
"SourceFilePath"));
StreamResult res = new StreamResult(new File(
"DestinantionFilePath"));
TransformerFactory.newInstance().newTransformer().transform(src, res);
是否可以使用 SAX 解析器来做到这一点,并且只保留具有 as false 的“规则”?
【问题讨论】: