如果子节点值满足参数,则在XML节点中获取属性值

时间:2014-11-25 19:40:04

标签: xml vbscript

我希望根据过滤后的子节点值Name获取属性值Location = 'Local'。源XML看起来像这样:

<?xml version="1.0"?>
<Root>
   <User Name="user1">
    <Element CreationDate="2014-11-16 18:05:44" ID="0a962d93-64e8-4caa-8a4d-e6e9b7df5af4" Name="ClienName1">
      <AdditionalInfo>
        <Client />
        <Number />
        <MasterMachine>LocalMachine1</MasterMachine>
       <Location>Local</Location>
       <Owner>Owner1</Owner>
      </AdditionalInfo>
    </Element>
    <Element CreationDate="2014-11-21 16:08:53" ID="65ddadf1-f7e4-467c-aedf-3d6ba5c35d1d" Name="ClienName2">
      <AdditionalInfo>
        <Client />
        <Number />
        <MasterMachine>LocalMachine1</MasterMachine>
        <Location>Local</Location>
        <Owner>Owner1</Owner>      
      </AdditionalInfo>
    </Element>
    <Element CreationDate="2014-11-24 10:00:13" ID="469479c7-a249-4bf4-a486-fc09b13ba145" Name="ClienName3">
      <AdditionalInfo>
        <Client />
        <Number />
        <MasterMachine>ServerMachine1</MasterMachine>
        <Location>Server</Location>
        <Owner>Owner2</Owner>
      </AdditionalInfo>
    </Element>
  </User>
</Root>

到目前为止我所拥有的是:

Set objXML = CreateObject("MSXML2.DOMDocument")
objXML.setProperty "SelectionLanguage", "XPath"
objXML.Load XML
Set objElementNode = objXML.selectNodes("//Root/User/Element/@Name")
Set objLocationNode = objXML.selectNodes("//Root/User/Element/@Name/AdditionalInfo [Location='Local']/Location")

For Each elementName In objElementNode
    For Each location In objLocationNode
        strMessage = elementName.text &" "& location.text &vbCr
    Next
Next
MsgBox strMessage

显然,我对这个领域一无所知。到目前为止,这是基于我在网上看到的片段而不了解如何遍历节点。

1 个答案:

答案 0 :(得分:0)

搜索具有值Local的子Location的AdditionalInfo,并获取其父级的Name属性:

在代码中:

  Dim oFS      : Set oFS      = CreateObject("Scripting.FileSystemObject")
  Dim sFSpec   : sFSpec       = goFS.GetAbsolutePathName("..\testdata\xml\27135249.xml")
  Dim objMSXML : Set objMSXML = CreateObject("Msxml2.DOMDocument")
  objMSXML.setProperty "SelectionLanguage", "XPath"
  objMSXML.async = False
  objMSXML.load sFSpec

  If 0 = objMSXML.parseError Then
     Dim sXPath : sXPath = "Root/User/Element/AdditionalInfo[Location=""Local""]"
     Dim ndlX : Set ndlX = objMSXML.selectNodes(sXPath)
     If 0 = ndlX.length Then
        WScript.Echo sXPath, "failed"
     Else
        Dim ndX
        For Each ndX In ndlX
            WScript.Echo "Name:", ndX.parentNode.GetAttribute("Name")
        Next
     End If
  Else
     WScript.Echo objMSXML.parseError.reason
  End If