XML DOM用于获取标记内的文本

时间:2016-04-18 07:51:30

标签: xml dom xpath vbscript

我有一个XPath查询//*[local-name()='Home Query Data'],经过测试here。 现在我必须执行此XPath以返回<Home Query Data> --- </Home Query Data>标记内的所有文本。

我应该使用哪个DOM选择器从标签中选择整个文本? 喜欢:objMSXML.selectNodes(XPath)

修改

我正在使用VBScript进行编程。我的代码如下:

Sub ReadXml(FileName)
  Dim nodeinfo (4)
  Dim sXPath
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set fileObj = fso.GetFile(FileName)
  objMSXML.async = True
  objMSXML.load FileName

  If 0 = objMSXML.parseError Then
  sXPath = "//*[local-name()='Home Query Data']"
  End If
  Dim querySubject : Set querySubject = objMSXML.selectSingleNode(sXPath)
  If querySubject Is Nothing Then
    MsgBox sXPath, "failed" ** Error type mismatch [string "failed"]**
  Else
    For Each node In objMSXML.selectNodes(sXPath)
      MsgBox node
    Next
  End If
End Sub

我已将其复制到其他帖子中,无法弄清楚如何在XML标记内返回整个文本。

我在这部分遇到了问题:

Dim querySubject : Set querySubject = objMSXML.selectSingleNode(sXPath)
If querySubject Is Nothing Then
  MsgBox sXPath, "failed"
Else
  For Each node In objMSXML.selectNodes(sXPath)
    MsgBox node
  Next
End If

EDIT2

我的工作XML就像:

<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
   <name locale="en">Stage Query Data</name>
  <price>$5.95</price>
  <description>Our famous Belgian Waffles with plenty of real maple syrup</description>
  <calories>650</calories>
</food>
<drink>
   <name locale="en">Home Query Data</name>
  <price>$4.50</price>
  <description>Thick slices made from our homemade sourdough bread</description>
  <calories>600</calories>
</drink>
<mix>
   <name locale="en">Report Query Data</name>
  <price>$6.95</price>
  <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
  <calories>950</calories>
</mix>
</breakfast_menu>

我需要捕获名称为<drink>的标记Home Query Data中的文字。

<name locale="en">Home Query Data</name>
      <price>$4.50</price>
      <description>Thick slices made from our homemade sourdough bread</description>
      <calories>600</calories>

目前我正在使用MsgBox sXPath,“失败”**错误类型不匹配[string“failed”] **

1 个答案:

答案 0 :(得分:1)

您应该使用text()属性选择器,而不是local-name()函数。后者获取节点的名称,而不是其内容。

此外,您的MsgBox来电无效 - 请参阅https://msdn.microsoft.com/en-us/library/sfw6660x%28v=vs.84%29.aspx

以下按预期方式工作:

Sub ReadXML(FileName)
  Dim sXPath
  Set objMSXML = CreateObject("Msxml2.DOMDocument.6.0")
  objMSXML.load FileName

  If objMSXML.parseError = 0 Then
    sXPath = "//*[name/text()='Home Query Data']"
    Dim querySubject : Set querySubject = objMSXML.selectSingleNode(sXPath)
    If querySubject Is Nothing Then
      MsgBox sXPath, 0, "failed"
    Else
      For Each node In objMSXML.selectNodes(sXPath)
        MsgBox node.text
      Next
    End If
  Else
    MsgBox objMSXML.parseError
  End If
End Sub