使用SAX解析XML,并根据值只获取一个元素


你好,我正在尝试使用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>

由于标签具有值"0";"假";,所以我主要想根据元素的值来过滤循环元素

到目前为止,代码帮助我过滤所有基于父元素但不基于元素的元素。

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解析器来做到这一点,并且只保留";规则";有一个作为假的?

这并不容易,因为它需要前瞻性-在稍后看到allow值之前,您无法决定如何处理rule开始标记。最简单的方法是开始为每个规则构建一个DOM(或类似DOM(树,当您点击rule结束标记时,决定是保留它还是放弃它

如果你想要一个使用XSLT3.0的流式解决方案来解决这个问题,那就是

<xsl:mode streamable="yes" on-no-match="shallow-copy"/>
<xsl:template match="rule">
<xsl:sequence select="copy-of(.)[condition/allow='true']"/>
</xsl:template>

最新更新