我是XML新手。我现在有一个要求,我必须从一堆XML文件中提取数据。我无法显示整个XML文件,但希望有人可以告诉我如何执行此操作。我已经阅读了很多论坛和博客,我很困惑。这是XML。
<?xml version="1.0"?>
<docpms>
<distrib>
<mrc>
<toolsetc>
<misc>
<seqlist>
<item spinno="02">
<paratext>Gloves</paratext>
</item>
<item spinno="022">
<paratext>Pail</paratext>
</item>
<item spinno="03">
<paratext>Lanyard</paratext>
</item>
<item spinno="07">
<paratext>Goggles</paratext>
</item>
&#13;
因此,我想循环遍历具有spinno属性的项节点并获取属性的文本值。还有许多其他项目节点没有这个属性,所以我想我需要使用类似下面的VBA。
Option Compare Database
Option Explicit
Dim xDoc As MSXML2.DOMDocument60
Dim strpath As String
Dim spinAttribute As MSXML2.IXMLDOMAttribute
Public Sub LoadDocument()
strpath = Environ("USERPROFILE") & "\Documents\XML\00\"
Set xDoc = New MSXML2.DOMDocument60
xDoc.validateOnParse = False
If (xDoc.Load(strpath & "1C.xml")) Then
' The document loaded successfully.
' Now do something intersting.
DisplayNode xDoc.childNodes, 0
Else
' The document failed to load.
' See the previous listing for error information.
End If
End Sub
Public Sub DisplayNode(ByRef Nodes As MSXML2.IXMLDOMNodeList, _
ByVal Indent As Integer)
Dim strSpin As String
Dim xNode As MSXML2.IXMLDOMNode
Set xNode = xDoc.selectNodes("/docpms/mrc/toolsetc/misc/seqlist/item")
For Each xNode In Nodes
Set spinAttribute = xNode.Attributes.getNamedItem("spinno")
strSpin = spinAttribute.Text
Next xNode
End Sub
&#13;
但是当我逐步执行代码时,我在Set xNode = xDoc.selectNodes(&#34; / docpms / mrc / toolsetc / misc / seqlist / item&#34;)上遇到了类型不匹配的问题,对于初学者而言我是不确定我的每个循环是否会做我想要的。任何帮助将不胜感激。
谢谢,
大卫
答案 0 :(得分:4)
我在Stack Overflow的另一篇论坛帖子中找到了答案。对不起我今天早些时候没有看到这个。这是答案How I can read all Attributes from a XML with VBA?,这是我的最终代码。
Private Sub Workbook_Open()
Dim spin As String
Dim xmlUrl As String
Dim xmlDoc As New DOMDocument
Dim n As IXMLDOMNode
Dim nText As String
xmlUrl = Environ("USERPROFILE") & "\Documents\Viewer\XML\00\001C.xml"
xmlDoc.async = False
If Not xmlDoc.Load(xmlUrl) Then
MsgBox "XML LOAD ERROR"
Else
For Each n In xmlDoc.selectNodes("//misc/seqlist/item")
spin = n.Attributes.getNamedItem("spinno").Text
nText = n.Text
Next
End If
End Sub
&#13;
这会搜索并获取我需要的所有属性值。
谢谢,
大卫
答案 1 :(得分:0)
您可以使用XPath仅选择具有该属性的节点:
Dim iNodes, n
Set xDoc = New MSXML2.DOMDocument60
xDoc.validateOnParse = True
xDoc.LoadXML Sheet1.Range("a1").Value 'my testing
xDoc.setProperty "SelectionLanguage", "XPath" '<<<######
'I simplified your XML a bit, so adjust here....
Set iNodes = xDoc.SelectNodes("/docpms/seqlist/item[@spinno]")
Debug.Print iNodes.Length
For Each n In iNodes
Debug.Print n.Text 'all itens with the spinno attribute
Next n