Xpath和命名空间,选择节点迭代器

时间:2013-08-21 12:06:49

标签: java xpath namespaces xml-namespaces

我有这种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 / correct / attachments / attachment”,“rda”,   “http://schemas.pkh.hr/doc/2013/documents/rda_30”)

3 个答案:

答案 0 :(得分:1)

/rda:documentAnswer/correct/attachments/attachment

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

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

不幸的是,XPath标准不支持声明默认命名空间。

答案 1 :(得分:0)

3种方法:

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

带有更正的标题:

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

的xpath

    /ns0:documentAnswer

B-Query仅查询具有local-name()函数的本地名称

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

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

    /*[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

答案 2 :(得分:0)

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

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