我有一个大型XML文件,我试图使用DOM进行解析。我尝试做的只是从节点中提取信息,如果它的父节点包含特定的" id"属性。
例如,如果我只想为包含" id = Adventure"的书籍拉出TITLE或AUTHOR。 - 我怎么用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>
现在使用此代码:
Sub mySub()
Dim mainWorkBook As Workbook
Dim XCMFILE As Variant
Dim BookType As String
Dim BookTitle As Variant
Dim Title As String
Dim n As IXMLDOMNode
Dim i As Integer
Set mainWorkBook = ActiveWorkbook
Set XCMFILE = CreateObject("Microsoft.XMLDOM")
XCMFILE.Load (XCMFileName) 'Load XCM File
i = 0
For Each n In XCMFILE.SelectNodes("/catalog/book")
BookType= n.Attributes.getNamedItem("id").Text 'Search for id attribute within node
If BookID = "Adventure" Then
Set BookTitle = = XCMFILE.SelectNodes("/catalog/book/title/text()")
Title = BookTitle(i).NodeValue
mainWorkBook.Sheets("Sheet1").Range("B" & i + 3).Value = BookTitle'Prints values into B column
i = i + 1
EndIf
Next
End Sub
我不知道如何正确增加以仅提取符合我的规范/类别的节点。
感谢您的任何提示和指示 - 我很感激。
答案 0 :(得分:1)
你不需要增加任何东西。只需编写一个XPath查询,只选择您感兴趣的节点:
For Each n In XCMFILE.SelectNodes("/catalog/book[@id=""Adventure""]")
' n is a book node with the "id" attribute value "Adventure"
Next