如何从由其属性指定的元素中获取childnode.element.text?

时间:2013-11-20 16:18:56

标签: xml vbscript xmldom

我有一个看起来像这样的xml文件;

[data.xml中]

<?xml version="1.0"?>
    <elem1 id="obj1">
        <celem1>Text1</celem1><celem2>Text2</celem2>
    </elem1>
    <elem2 id="obj2">
        <celem1>Text3</celem1><celem2>Text4</celem2>
    </elem2>

一个看起来像这样的读取xml函数;

Function GetVar(XMLTag, strNum)
   Set oXMLFile = CreateObject("Msxml2.DOMDocument")
       oXMLFile.Load("data.xml")
   Set oXMLFileVariable = oXMLFile.getElementsByTagName(XMLTag)
       GetVar = oXMLFileVariable.Item(strNum).Text
End Function

调用这样的函数;

    Call GetVar("celem1", 0)
    Call GetVar("celem2", 0)
    Call GetVar("celem1", 1)
    Call GetVar("celem2", 1)

将返回;

“文本1”
“文本2”
“文本3”
“text4” 中

我希望能够通过指定其parentnode的属性来返回childnode element.text。这样的事情;

[伪代码 - 原谅我,如果我离开这里的话]

    GetChildNode.Text(elem1(GetAttribute="obj1").celem1())

会返回类似的内容;

“文本1”

我问的原因是因为我想删除特定元素名称而不是通用元素名称,然后能够通过指定属性来调用特定的element.text信息。我不喜欢为xml doc中的每个新条目创建和维护一个唯一的元素标记。

我目前正在使用VBscript,但我可以改为其他可以工作的东西(windows环境)。

[--- --- EDIT]

使用Ansgar Wiechers示例,我创建了以下内容;

[data.xml中]

<?xml version="1.0"?>
  <elem id="obj1">
      <celem id="item1">Text1</celem><celem id="item2">Text2</celem>
  </elem>
  <elem id="obj2">
      <celem id="item1">Text3</celem><celem id="item2">Text4</celem>
  </elem>

和脚本;

str1 = GetVar("obj1", "celem", "item1")
str2 = GetVar("obj2", "celem", "item2")
MsgBox str1
MsgBox str2

Function GetVar(parentID, childNode, childAtt)
    GetVar = Null 'set a safe default return value

    Set oXMLFile = CreateObject("Msxml2.DOMDocument.6.0")
    oXMLFile.async = False
    oXMLFile.Load "xpath.xml"

    If oXMLFile.parseError = 0 Then
            xpath = "//*[@id='" & parentID & "']/" & childNode _
               & "[@id='" & childAtt & "']"
            Set node = oXMLFile.selectSingleNode(xpath)
            If Not node Is Nothing Then GetVar = node.text
    Else
            'report errors
            WScript.Echo oXMLFile.parseError.reason
    End If
End Function


第一个MsgBox将返回 “Text1”
第二个MsgBox将返回 “Text4”

这正是我所寻找的!

1 个答案:

答案 0 :(得分:0)

使用XPath expression选择节点:

Function GetVar(parentId, childNode)
  GetVar = Null  'set a safe default return value

  Set oXMLFile = CreateObject("Msxml2.DOMDocument.6.0")
  oXMLFile.async = False
  oXMLFile.load "data.xml"

  'Without having set async to False the above instruction would load the
  'file in the background, so your code would try to process data that
  'isn't completely loaded yet.

  If oXMLFile.parseError = 0 Then
    xpath = "//*[@id='" & parentId & "']/" & childNode
    Set node = oXMLFile.selectSingleNode(xpath)
    If Not node Is Nothing Then GetVar = node.text
  Else
    'report errors
    WScript.Echo oXMLFile.parseError.reason
  End If
End Function

XPath表达式//*[@id='obj1']/celem1表示:选择具有属性<celem1>且值为id的父节点的任何节点obj1。通过使用selectSingleNode方法,您只需选择第一次出现此类节点(如果有)。

如果可以有多个匹配节点并且您不想只返回返回的第一个节点的值,则需要定义如何处理其他节点的值。

相关问题