3

我想问一下是否有人知道如何使用 XPath 查询进行 XSD 1.1 条件类型分配检查元素是否没有属性,例如:

<!--inline alternative type definitions --> 
<element name="TimeTravel" type="TravelType"> 
      <alternative test="@direction='Future'"> 
          <complexType> 
              <complexContent> 
              <restriction base="TravelType" 
                         .... 
<!--        some past travel related elements go here --> 
            </complexType> 
       </alternative> 
      <alternative test="@direction='Past'"> 
          <complexType> 
              <complexContent> 
              <restriction base="TravelType" 
                         .... 
   <!--        some future travel related elements go here --> 
            </complexType> 
       </alternative> 
  </element> 
                          OR 
<!--Named alternative type definitions --> 
<element name="TimeTravel" type="TravelType"> 
   <alternative test="@direction='Future' type="FutureTravelType"/> 
   <alternative test="@direction='Past' type="PastTravelType"/> 
</element>

在本例中,'alternative test=""' 检查 TimeTravel 元素的属性“direction”是否具有“Future”或“Past”的值。我应该如何编写 XPath 查询来检查当前元素是否没有“direction”属性?

4

1 回答 1

7

XPath"@direction"将测试当前元素上是否存在属性:direction

<alternative test="@direction" type="DirectionType"/>

XPath"not(@direction)"将测试当前元素上是否缺少属性:direction

<alternative test="not(@direction)" type="NoDirectionType"/>

另请注意,alternative/@test可以完全省略该属性以提供默认类型。

<alternative type="DefaultType"/>

根据 OP 的后续问题更新以解决 CTA 子集模式

所以这<alternative test="@direction='a_value' and not(@another_attribute)"/>是正确的并且会正确吗?

是的,但请注意,您的 XSD 处理器可能默认使用 XPath CTA(条件类型分配)子集。(例如,Xerces 以及大多数基于 Xerces 的工具都执行此操作。)如果是这种情况,您将收到如下所示的错误:

c-cta-xpath:在 CTA 评估期间,XPath 表达式“not(@direction)”无法在“cta-subset”模式下成功编译。

c-cta-xpath:在 CTA 评估期间,XPath 表达式 '@direction='a_value' 和 not(@another_attribute)' 无法在 'cta-subset' 模式下成功编译。

要使用完整的 XPath 2.0 而不是 CTA 子集,请相应地配置您的工具。例如,对于 Xerces,将以下功能设置为“真”:

http://apache.org/xml/features/validation/cta-full-xpath-checking

在 oXygen 中,有一个复选框Options > Preferences > XML > XML Parser > XML Schema可以为您控制功能的值。

是的,使用完整的 XPath 2.0,您可以and按照您在评论中建议的方式使用。

于 2014-08-07T20:21:44.913 回答