Xml VBA DOM特定的节点和属性ID
我有一个很大的XML文件,我正试图用DOM解析它。我试图做的是从属性节点中提取信息,如果它的子节点包含某个值 比如说,Xml VBA DOM特定的节点和属性ID,xml,vba,dom,xml-parsing,attributes,Xml,Vba,Dom,Xml Parsing,Attributes,我有一个很大的XML文件,我正试图用DOM解析它。我试图做的是从属性节点中提取信息,如果它的子节点包含某个值 比如说, <?xml version="1.0"?> <catalog> <book id="Adventure"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <price&
<?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>
现在,如果我想在下一个专栏中显示图书类型(即“冒险/神秘”),我会怎么做?我试着向后思考,但我甚至不知道如何开始
我知道我可以使用XPath和IXMLDOMNode来获取属性id,但我只是不知道如何实际执行此操作,因为它似乎是反向的
感谢您提供的提示和建议,我非常感谢。您可以“向上”几个步骤,进入父级“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
嘿,蒂姆,谢谢你的回应和帮助。如果您不介意的话,只需要一个简单的问题:如果我想将BookType值存储到数组中,我会将一个新数组
Dim myStr()定义为String
,然后将myStr()=Author(I).ParentNode.ParentNode.getAttribute(“id”)
放在With语句中吗?这样,如果需要的话,我可以稍后在循环外打印这些值。您只能一个接一个地分配这些值,并且在添加每个项目时需要调整数组的大小,但是可以这样做。
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