【问题标题】:Parse XML using SAX and get only one element based on value使用 SAX 解析 XML 并根据值仅获取一个元素
【发布时间】: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 的“规则”?

【问题讨论】:

    标签: java xml parsing sax


    【解决方案1】:

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

    如果您想要使用 XSLT 3.0 解决此问题的流式解决方案,那么

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

    【讨论】:

    • 感谢您的提醒!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2012-04-03
    • 2011-06-29
    • 2012-09-10
    • 2014-02-27
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多