仅当子元素不存在时才通过XPath选择属性?

时间:2016-04-28 14:40:02

标签: xml xpath xpath-1.0

我有一个示例XML片段,如下所示

<asdiOutput xmlns="http://tfm.faa.gov/tfms/TFMS_XIS" xmlns:nxce="http://tfm.faa.gov/tfms/NasXCoreElements" 
    xmlns:mmd="http://tfm.faa.gov/tfms/MessageMetaData" 
    xmlns:nxcm="http://tfm.faa.gov/tfms/NasXCommonMessages" 
    xmlns:idr="http://tfm.faa.gov/tfms/TFMS_IDRS" 
    xmlns:xis="http://tfm.faa.gov/tfms/TFMS_XIS"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://tfm.faa.gov/tfms/TFMS_XIS http://localhost:58489/tfms/schema/TFMS_XIS.xsd" 
    timestamp="2011-03-15T23:57:59Z">
  <asdiMessage sourceFacility="CCZM" sourceTimeStamp="2011-03-15T23:57:27Z" trigger="TZ">
    <trackInformation>
      <nxcm:aircraftId>UAL966</nxcm:aircraftId>
      <nxcm:speed>470</nxcm:speed>
      <nxcm:reportedAltitude>
        <nxce:assignedAltitude>
          <nxce:simpleAltitude>350</nxce:simpleAltitude>
        </nxce:assignedAltitude>
      </nxcm:reportedAltitude>
      <nxcm:position>
        <nxce:latitude>
          <nxce:latitudeDMS degrees="45" minutes="40" direction="NORTH"/>
        </nxce:latitude>
        <nxce:longitude>
          <nxce:longitudeDMS degrees="056" minutes="58" direction="WEST"/>
        </nxce:longitude>
      </nxcm:position>
   </trackInformation>
  </asdiMessage>
  <asdiMessage sourceFacility="CCM" sourceTimeStamp="2015-03-15T23:57:27Z" trigger="TZ">
    <trackposition>
      <nxcm:aircraftId>UAL936</nxcm:aircraftId>
      <nxcm:speed>470</nxcm:speed>
      <nxcm:reportedAltitude>
        <nxce:assignedAltitude>
          <nxce:simpleAltitude>350</nxce:simpleAltitude>
        </nxce:assignedAltitude>
     </nxcm:reportedAltitude>
      <nxcm:position>
        <nxce:latitude>
          <nxce:latitudeDMS degrees="44" minutes="43" direction="NORTH"/>
        </nxce:latitude>
        <nxce:longitude>
          <nxce:longitudeDMS degrees="062" minutes="42" direction="WEST"/>
        </nxce:longitude>
      </nxcm:position>
    </trackposition>
  </asdiMessage>
</asdiOutput>

我想提取值 sourceFacility="CCZM"sourceTimeStamp="2011-03-15T23:57:27Z"trigger="TZ"

但是XPath不应该返回asdiMessage的值,该值包含一个名为trackposition的子元素。 因此不应返回以下值: asdiMessage sourceFacility="CCM" sourceTimeStamp="2015-03-15T23:57:27Z" trigger="TZ"因为子元素。

我试过这个/asdiOutput/asdiMessage[not(contains(trackposition))],但这根本不会返回任何内容

1 个答案:

答案 0 :(得分:0)

首先,修复根元素的结束标记中的拼写错误:

</asdiOuput>应为</asdiOutput>

接下来,确保为http://tfm.faa.gov/tfms/TFMS_XIS定义了名称空间前缀:

xis="http://tfm.faa.gov/tfms/TFMS_XIS"

然后,这个XPath,

/xis:asdiOutput/xis:asdiMessage[not(xis:trackposition)]/@sourceFacility

将根据要求选择"CCZM"

您可以类似地为sourceTimeStamptrigger构建XPath。