xml - XML节点的VBScript位置,用作到另一个节点的索引

标签 xml xpath vbscript wsh

我有以下XML:

adapt.xml:    
 <Adapters>
   <Adapter>
    <IPAddresses>
      <IPAddress>1.1.1.1</IPAddress>
      <IPAddress>2.2.2.2</IPAddress>
      <IPAddress>3.3.3.3</IPAddress>
    </IPAddresses>
    <IPSubnets>
      <IPSubnet>255.0.0.0</IPSubnet>
      <IPSubnet>255.255.0.0</IPSubnet>
      <IPSubnet>255.255.255.0</IPSubnet>
    </IPSubnets>
  </Adapter>
</Adapters>


我正在尝试将选定的IPAddress与相应的IPSubnet对齐,如下所示:

Set adaptersDoc = CreateObject("Microsoft.XMLDOM")
adaptersDoc.SetProperty "SelectionLanguage", "XPath"
adaptersDoc.Async = False
adaptersDoc.Load("adapt.xml")

For Each ipNode In adaptersDoc.selectNodes("//IPAddresses/IPAddress")
    WScript.Echo "ipNode", ipNode.Text
    WScript.Echo "subnet", ipNode.selectSingleNode("//IPSubnets/IPSubnet[ count(preceding-sibling::IPAddress)+1 ]").Text
Next


我当前的输出是这样的:

ipNode 1.1.1.1
subnet 255.0.0.0
ipNode 2.2.2.2
subnet 255.0.0.0
ipNode 3.3.3.3
subnet 255.0.0.0


我想要的输出是这样的:

ipNode 1.1.1.1
subnet 255.0.0.0
ipNode 2.2.2.2
subnet 255.255.0.0
ipNode 3.3.3.3
subnet 255.255.255.0


我正在尝试让xpath选择IPSubnet元素相对于IPAddress位置的相同位置。

显然,count(preceding-sibling :: IPAddress)并未执行我认为应该做的事情。

似乎这应该起作用,因为节点上下文知道它是之前和之后的同级节点,但是当我尝试将其用作IPSubnet [x]的索引时,它并没有给我想要的结果。

我需要在XPath字符串中执行此操作,而不是通过更改程序来执行诸如迭代节点之类的工作,并使用节点或childNodes的计数器或长度。

有什么建议?

最佳答案

我认为您的假设不正确。通过执行//IPSubnets/IPSubnet,节点上下文更改为<IPSubnet>。在这种情况下,调用count(preceding-sibling::IPAddress)始终会产生0,因为XML中的<IPSubnet>之前没有任何同级的<IPAddress>。这就是为什么您在每次迭代中都得到//IPSubnets/IPSubnet[1]-其值为255.255.255.0-的原因。

我能得到的最接近的东西是这样的:

For Each ipNode In adaptersDoc.SelectNodes("//IPAddresses/IPAddress")
    WScript.Echo "ipNode", ipNode.Text
    xpath = "//IPSubnets/IPSubnet[position() = count(//IPAddresses/IPAddress[.='" & ipNode.Text & "']/preceding-sibling::IPAddress)+1]"
    WScript.Echo "subnet", ipNode.SelectSingleNode(xpath).Text
Next


输出:

ipNode        1.1.1.1
subnet        255.0.0.0
ipNode        2.2.2.2
subnet        255.255.0.0
ipNode        3.3.3.3
subnet        255.255.255.0

关于xml - XML节点的VBScript位置,用作到另一个节点的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29789346/

相关文章:

vbscript - sAMAccountName 和区分大小写

C# LinQ to XML 创建输出

java - 如何使用 java 根据 DTD 验证 XML?

javascript - 使用 javascript 的 xml 属性缺少结束标记

python - python 的 lxml 中的正则表达式

xpath - XQuery 中是否有任何方法可以获取自某个 Epoch 以来以毫秒为单位的当前时间?

vbscript - 需要使用命令提示符打开本地镜像文件的 VBScript

c# - 将 RSS feed 转换为 DataTable

python-3.x - 从<span>标签元素获取文本

vbscript - 通过 VBScript 了解用户是否具有管理权限的最佳方法