我试图找出具有特定值的 XML 属性是否存在于 xml 文档根的每个子元素中。我的代码如下:
Option Explicit
Dim sheet As Worksheet
Dim rowCount1, i As Integer
Dim xNode As MSXML2.IXMLDOMNode
Dim xDoc As MSXML2.DOMDocument
Dim Nodes As MSXML2.IXMLDOMNodeList
Public Sub LoadDocument()
rowCount1 = 0
Set xDoc = New MSXML2.DOMDocument
xDoc.validateOnParse = False
If xDoc.load("D:\Feedroutes.xml") Then ' The document loaded successfully.
Set Nodes = xDoc.SelectNodes("//Property[@name='Value']")
AttributesToColumns
Else
' The document failed to load.
End If
End Sub
Public Sub AttributesToColumns()
Set sheet = ActiveSheet
For Each xNode In Nodes
If Not Nodes Is Nothing Then
rowCount1 = rowCount1 + 1
sheet.Cells(rowCount1, 3).Value = xNode.Text
'I want to increment the rowCount even if the attribute with the
'specific value doesn't exist
ElseIf Nodes Is Nothing Then
rowCount1 = rowCount1 + 1
End If
Next xNode
End Sub
目前它只在连续的行中写入属性的值,而所需的输出是,只在存在具有特定值的属性的行中写入。我的 XML 如下所示:
<Tag name="PosLim" path="Feeders/R1" type="OPC">
<Property name="Value">0.0</Property>
<Property name="DataType">4</Property>
<Property name="OPCServer">Ignition OPC-UA Server</Property>
<Property name="OPCItemPath">[Siemens]DB141,I74</Property>
<Property name="ScaleMode">1</Property>
<Property name="RawHigh">1000.0</Property>
<Property name="FormatString">#,##0.00</Property>
<Property name="EngUnit">Kg</Property>
</Tag>
<Tag name="JogSettle" path="Feeders/R1" type="OPC">
<Property name="DataType">1</Property>
<Property name="OPCServer">Ignition OPC-UA Server</Property>
<Property name="OPCItemPath">[Siemens]DB141,I96</Property>
<Property name="RawHigh">1000.0</Property>
<Property name="FormatString">#,##0</Property>
<Property name="EngUnit">S</Property>
</Tag>
<Tag name="Positive Tol" path="Feeders/R1" type="OPC">
<Property name="Value">0.0</Property>
<Property name="DataType">4</Property>
<Property name="OPCServer">Ignition OPC-UA Server</Property>
<Property name="OPCItemPath">[Siemens]DB141,I78</Property>
<Property name="ScaleMode">1</Property>
<Property name="RawHigh">1000.0</Property>
<Property name="FormatString">#,##0.00</Property>
<Property name="EngUnit">Kg</Property>
</Tag>
我的目的是在相应的行中写入属性“name”的值,其中 name =“Value”以及所有其他属性,而不是连续的行。所以从上面的 xml 文件中,我的 excel 输出应该是:
Row No. Value ScaleMode
Row1 0 1
Row2
Row3 0 1 etc