XPath查询通过某些实现选择元素

时间:2012-04-10 07:30:41

标签: xml xpath

http://www.namspace.org/impl中选择 XYZImpl 实施的“抽象”节点的正确查询是什么

<...>
  <Abstract xmlns:q3="http://www.namspace.org/impl"
                xsi:type="q3:XYZImpl">
    <...></...>
  </Abstract>
  <Abstract xmlns:q8="http://www.namspace.org/another"
                xsi:type="q8:XYZImpl">
    <...></...>
  </Abstract>
 </...>

订单和名称空间前缀在我的控制下

如果文档只包含唯一的实现,则以下查询“有效”:

//Abstract[contains(@xsi:type,'XYZImpl')]

但我正在寻找完全限定名称(名称空间+名称)的正确规范...:/

2 个答案:

答案 0 :(得分:2)

使用

   /*/Abstract
       [substring-after(@xsi:type, ':') = 'XYZImpl']
          [namespace::*
              [name() = substring-before(../@xsi:type, ':')
              and
               . = 'http://www.namspace.org/impl'
              ]
          ]

这将选择XML文档顶部元素的任何Abstract子元素,该子元素具有带前缀的命名空间,该前缀也是其xsi:type属性中包含的QName值的前缀。 xsi:type属性中包含的QName值的“local-name”部分恰好是字符串"XYZImpl"

基于XSLT的验证

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xsi="some:xsi">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
     <xsl:copy-of select=
      "/*/Abstract
           [substring-after(@xsi:type, ':') = 'XYZImpl']
              [namespace::*
                  [name() = substring-before(../@xsi:type, ':')
                  and
                   . = 'http://www.namspace.org/impl'
                  ]
              ]
      "/>
 </xsl:template>
</xsl:stylesheet>

将此转换应用于以下XML文档(由提供,通过使其格式正确):

<t xmlns:xsi="some:xsi">
      <Abstract xmlns:q3="http://www.namspace.org/impl"
                    xsi:type="q3:XYZImpl">
       </Abstract>
      <Abstract xmlns:q8="http://www.namspace.org/another"
                    xsi:type="q8:XYZImpl">
      </Abstract>
</t>

选择所需的正确元素并将其复制到输出

<Abstract xmlns:q3="http://www.namspace.org/impl" xmlns:xsi="some:xsi" xsi:type="q3:XYZImpl"/>

请注意:为了成功评估XPath表达式,必须在XPath实现中注册前缀为xsi的相应名称空间。

答案 1 :(得分:0)

当然,使用有效样本回答xml问题会更容易....

这可能不是最好的方式,但以下内容对我有用:

//Abstract[namespace::*[.="http://www.namspace.org/impl"] and contains(@xsi:type,":XYZImpl")]