我有一个大型XML文件,我试图使用DOM进行解析。我想要做的是从属性节点中提取信息,如果它的孩子包含某个值。
例如,
<?xml version="1.0"?>
<catalog>
<book id="Adventure">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
</book>
<book id="Adventure">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
</book>
<book id="Adventure">
<author>Boal, John</author>
<title>Mist</title>
<price>15.95</price>
</book>
<book id="Mystery">
<author>Ralls, Kim</author>
<title>Some Mystery Book</title>
<price>9.95</price>
</book>
</catalog>
所以从这里开始,我想说要找到作者写的书&#34; Ralls,Kim&#34;:
Sub mySub()
Dim mainWorkBook As Workbook
Dim XMLFile As Variant
Dim BookType As String
Dim Author As Variant
Dim athr As String
Dim n As IXMLDOMNode
Dim i As Integer
Set mainWorkBook = ActiveWorkbook
Set XMLFILE = CreateObject("Microsoft.XMLDOM")
XMLFILE.Load (XCMFileName) 'Load XCM File
Set Author = XMLFILE.SelectNodes("/catalog/book/author/text()")
For i = 0 To (Author.Length - 1)
athr= Author(i).NodeValue
If athr = "Ralls, Kim" Then
mainWorkBook.Sheets("Sheet1").Range("C" & i + 3).Value = athr
End If
Next
End Sub
现在,如果我想在下一栏中显示书籍类型(即&#34;冒险/神秘&#34;),我该怎么做?我试图倒退,但我不知道如何开始这个。
我知道我可以使用XPath和IXMLDOMNode来获取属性id,但我不知道如何实际执行此操作,因为它似乎是倒退。
感谢您的任何提示和指示 - 我很感激。
答案 0 :(得分:0)
您可以“向上”几个步骤来访问父“book”元素并从那里阅读id
属性:
Sub mySub()
Dim mainWorkBook As Workbook
Dim XMLFile As Variant
Dim BookType As String
Dim Author As Variant
Dim athr As String
Dim n As IXMLDOMNode
Dim i As Long, x As Long
Set mainWorkBook = ActiveWorkbook
Set XMLFile = CreateObject("Microsoft.XMLDOM")
XMLFILE.Load (XCMFileName) 'Load XCM File
x = 3
Set Author = XMLFile.SelectNodes("/catalog/book/author/text()")
For i = 0 To (Author.Length - 1)
athr = Author(i).NodeValue
If athr = "Ralls, Kim" Then
With mainWorkBook.Sheets("Sheet1")
.Range("C" & x).Value = athr
.Range("D" & x).Value = _
Author(i).ParentNode.ParentNode.getAttribute("id")
End With
x = x + 1
End If
Next
End Sub