我试图只回归两位作者:“Ralls,Kim”和“Boal,John”。问题是“Ralls,Kimberly”也符合我的标准。有没有办法设置'精确'项目匹配,以便我可以避免这种情况?
<?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="Science-Adventure">
<author>Ralls, Kimberly</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 XMLFile As MSXML2.DOMDocument
Dim Author As Variant
Dim athr As String, BookType As String, Title As String
Dim AuthorArray() As String, BookTypeArray() As String, TitleArray() As String
Dim i As Long, x As Long, j As Long
Dim mainWorkBook As Workbook
Dim n As IXMLDOMNode
Set mainWorkBook = ActiveWorkbook
Set XMLFile = CreateObject("Microsoft.XMLDOM")
XMLFile.Load ("vba.xml")
x = 1
j = 0
Set Author = XMLFile.SelectNodes("/catalog/book/author")
For i = 0 To (Author.Length - 1)
ReDim Preserve AuthorArray(0 To i)
ReDim Preserve BookTypeArray(0 To i)
ReDim Preserve TitleArray(0 To i)
athr = Author(i).Text
BookType = Author(i).ParentNode.getAttribute("id")
Title = Author(i).ParentNode.getElementsByTagName("title").Item(0).nodeTypedValue
If athr = "Ralls, Kim" or athr = "Boal, John" Then
AuthorArray(j) = athr
BookTypeArray(j) = BookType
TitleArray(j) = Title
j = j + 1
x = x + 1
End If
Next
Range("A3:A" & UBound(AuthorArray) + 1) = WorksheetFunction.Transpose(AuthorArray)
Range("B3:B" & UBound(BookTypeArray) + 1) = WorksheetFunction.Transpose(BookTypeArray)
Range("C3:C" & UBound(BookTypeArray) + 1) = WorksheetFunction.Transpose(TitleArray)
End Sub
答案 0 :(得分:0)
这是另一个基于您的代码的更直接的实现,它可能会有所帮助。
Sub mySub()
Dim XMLFile As MSXML2.DOMDocument
Dim colBooks As Variant
Dim AuthorArray() As String, BookTypeArray() As String, TitleArray() As String
Dim i As Long
Dim k As Long
Cells.Clear
Set XMLFile = CreateObject("Microsoft.XMLDOM")
XMLFile.Load ("C:\Test\vba.xml")
Set colBooks = XMLFile.SelectNodes("/catalog/book[author='Ralls, Kim' or author='Boal, John']")
k = (colBooks.Length - 1)
ReDim AuthorArray(0 To k)
ReDim BookTypeArray(0 To k)
ReDim TitleArray(0 To k)
For i = 0 To k
AuthorArray(i) = colBooks(i).getElementsByTagName("author")(0).Text
BookTypeArray(i) = colBooks(i).getAttribute("id")
TitleArray(i) = colBooks(i).getElementsByTagName("title")(0).Text
Next
Range("A1:A" & UBound(AuthorArray) + 1) = WorksheetFunction.Transpose(AuthorArray)
Range("B1:B" & UBound(BookTypeArray) + 1) = WorksheetFunction.Transpose(BookTypeArray)
Range("C1:C" & UBound(BookTypeArray) + 1) = WorksheetFunction.Transpose(TitleArray)
End Sub