XML 元素具有命名空间,我的 XPATH 不起作用 [英] XML element has namespace, my XPATH does not work

查看:36
本文介绍了XML 元素具有命名空间,我的 XPATH 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下 XML:

I was given the following XML:

<root>
  <items>
    <item>
      <title>Item</title>
      <details>
        <data xmlns="http://some_url">
          <length>10</length>
          <weight>1.2</weight>
        </data>
      </details>
    </item>
  </items>
</root>

以下 XPath 不起作用意味着不会像数据"元素不存在那样打印任何内容:

Following XPath does not work meaning nothing is printed like the "data" element does not exists:

/root/items/item/details/data

但是当我删除data"元素的xmlns"命名空间属性时,它的内容被打印出来.在不删除data"元素的xmlns"命名空间属性的情况下,xpath 表达式应该如何工作?

But when I remove "xmlns" namespace attribute of "data" element it's content is printed. How should the xpath expression look like to work without deleting "xmlns" namespace attribute of "data" element?

我使用的是 SAXON 和 XSL 1.0.

I'm using SAXON and XSL 1.0.

推荐答案

这是 XPath/XSLT 中最常见的常见问题之一:

XPath 将无前缀的元素名称解释为属于无命名空间",这就是当仅将其无前缀名称指定为节点测试时,不选择具有属于默认(非空)命名空间的无前缀名称的元素的原因一个 XPath 表达式.

XPath interprets an unprefixed element name as belonging to "no namespace" and this is the reason elements with unprefixed names belonging to a default (nonempty) namespace aren't selected when only their unprefixed name is specified as a node-test in an XPath expression.

解决方案是:

  1. 创建一个命名空间绑定,其中前缀(比如 "x")与默认命名空间相关联,然后指定 x:elementName 而不是 元素名称.

  1. Create a namespace binding where a prefix (say "x") is associated with the default namespace, then specify x:elementName instead of elementName.

使用冗长、丑陋和不可靠的表达式,例如:*[name() = 'elementName']

Use long, ugly and unreliable expressions like: *[name() = 'elementName']

这是使用上述方法的 XSLT 转换1.:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:a="http://some_url">
 <xsl:output method="text"/>

 <xsl:template match="/">
  <xsl:value-of select=
  "/root/items/item/details/a:data/a:weight"/>
 </xsl:template>
</xsl:stylesheet>

在提供的 XML 文档上应用此转换时(使用 Saxon 6.5.4 或任何其他兼容的 XSLT 1.0 处理器):

<root>
    <items>
        <item>
            <title>Item</title>
            <details>
                <data xmlns="http://some_url">
                    <length>10</length>
                    <weight>1.2</weight>
                </data>
            </details>
        </item>
    </items>
</root>

选择正确/想要的节点并将其字符串值复制到输出:

1.2

这篇关于XML 元素具有命名空间,我的 XPATH 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆