【问题标题】:Xpath and namespace, select node iteratorXpath 和命名空间,选择节点迭代器
【发布时间】:2013-08-21 12:06:48
【问题描述】:

我有这种 XML:

<?xml version="1.0" encoding="UTF-8"?>
<documentAnswer xmlns="http://schemas.pkh.hr/doc/2013/documents/rda_30" domainName="rda" domainVersion="3.0">
<answerTimestamp>2013-08-21T13:35:25.894</answerTimestamp>
<correct>
    <docId>RDA2_29F81D27-1409BE49E2E-7FF8</docId>
    <attachments>
        <attachment>
            <format>application/pdf</foraat>
            <generatedType>StampanNaBlanko</generatedType>
            <encodedPdf>JVBERiYKJSVFT0YK</encodedPdf>
        </attachment>
    </attachments>
</correct>

那些附件标签可以是一个或多个。我正在尝试使用

在 java 中获取 attachment 标签的 NodeIterator

XPathAPI.selectNodeIterator(节点, "/documentAnswer/正确/附件/附件")

然后迭代,但我没有成功。我猜测问题出在 xpath 中,并且与命名空间有关,但不知道如何解决。我尝试使用这种 xpath 但没有成功:

XPathAPI.selectNodeIterator(节点, "/rda:documentAnswer/正确/附件/附件", "rda", "http://schemas.pkh.hr/doc/2013/documents/rda_30")

【问题讨论】:

    标签: java xpath namespaces xml-namespaces


    【解决方案1】:
    /rda:documentAnswer/correct/attachments/attachment
    

    这里您只将rda 命名空间分配给根元素,但它在XML 中被声明为default 命名空间。因此,all 您的元素都在该命名空间中。你必须使用

    /rda:documentAnswer/rda:correct/rda:attachments/rda:attachment
    

    很遗憾,XPath 标准不支持默认命名空间的声明。

    【讨论】:

      【解决方案2】:

      3种方法:

      用于查询 QNames 而不仅仅是 local-names() 的 A-Embed 命名空间

      带有更正的标题:

      <ns0:documentAnswer xmlns:ns0="http://schemas.pkh.hr/doc/2013/documents/rda_30" domainName="rda" domainVersion="3.0">
      

      xpath

          /ns0:documentAnswer
      

      B-使用 local-name() 函数仅查询本地名称

          /*[local-name()="documentAnswer"]
      

      C-Query 本地名称和命名空间(查询 QName)

          /*[local-name()="documentAnswer" and namespace-uri()='http://schemas.pkh.hr/doc/2013/documents/rda_30']
      

      http://nealwalters.blogspot.fr/2005/01/common-xpath-examples-questions-issues.html

      【讨论】:

        【解决方案3】:

        如果你愿意,你可以通过这种方式忽略命名空间:

        /*:documentAnswer/*:correct/*:attachments/*:attachment
        

        【讨论】:

        • 仅在 XPath 2.0 中。如果这是我们正在讨论的 Xalan 的 XPathAPI,那么它只支持 XPath 1.0,它允许 prefix:* 但不允许 *:localname
        • @Ian Roberts,是的,你是对的。我的错误忽略它,对不起!
        猜你喜欢
        • 2010-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-10
        • 1970-01-01
        • 2011-05-23
        • 2015-08-09
        • 2013-11-29
        相关资源
        最近更新 更多