【问题标题】:unable to get xpath where parent and child node have different default namespaces无法获取父节点和子节点具有不同默认命名空间的 xpath
【发布时间】:2013-06-02 23:23:43
【问题描述】:

我遇到了一种情况,我必须使用 xslt 解析和转换给定的 XML。我需要编写 xpath 来执行此操作。

示例 xml 如下所示。其中 ServiceProviderGroupPackage 和 SecondNode 都有不同的命名空间。我需要获取 IReference 节点的命名空间来获取它的值。

<?xml version="1.0" encoding="utf-8" ?>
<ServiceProviderGroupPackage Version="1.2.0" xmlns="http://webconnectivity.co.uk/ServiceProviderGroupPackage"
                             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                             xmlns:wsa="http://www.w3.org/2005/08/addressing">
  <FirstNode Version="1.2.0" xmlns="http://www.MySite.org/Standards/MySiteMsgSvc/1"
                    xmlns:rlc="http://www.MySite.org/standards/SecondNode/1"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  </FirstNode>
  <SecondNode Version="2010-2" xmlns:ac="http://www.MySite.org/Standards/MySiteMsgSvc/1"
                      xmlns="http://www.MySite.org/standards/SecondNode/1"
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xmlns:lloyds="http://www.lloyds.com/The-Market/Operating-at-Lloyds/Resources/Risk_codes">
    <Movement Sender="Sender" Receiver="Receiver">
      <Contract>
        <Type>direct</Type>
        <Nature>lm_proportional_or_nonproportional</Nature>
        <Reference>B0509311011UMR</Reference>
        <IReference>P00000062MM/13A</IReference>
      </Contract>
    </Movement>
  </SecondNode>
</ServiceProviderGroupPackage>

【问题讨论】:

    标签: xml xslt xpath xml-namespaces


    【解决方案1】:

    如果没有被覆盖,每个元素都会继承父元素的命名空间,因此 IReference 元素与 SecondNode 元素具有相同的命名空间,http://www.MySite.org/standards/SecondNode/1


    要检索任意元素的命名空间,请使用namespace-uri(...) 函数。

    使用 XPath 2.0,您可以使用通配符运算符 * 代替命名空间前缀:

    namespace-uri(//*:IReference)
    

    也可以

    //*:IReference/namespace-uri()
    

    使用 XPath 1.0,您必须检查谓词中的名称:

    namespace-uri(//*[local-name() = "IReference"])
    

    【讨论】:

    • 按照您在我的 xslt 中的指示尝试使用 xpath。没有运气。它不读取 /* 的组合
    • 正如你所说,如果没有被覆盖,每个元素都会继承父级的命名空间,我应该在我的整个 xpath 中没有前缀。但不知何故不是这样的
    • 知道了...感谢您的指导。您需要使用前缀将命名空间添加到 xslt,然后使用节点所属的任何命名空间将它们添加到 xpath。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2023-03-14
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多