我有以下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/