这似乎应该很容易,但它没有按预期工作。首先,我将发布XML,然后发布我拥有的VBA。不幸的是,我无法发布整个XML文件。
-<item id="ref4">
<paratext>Reinstall tire retainers, if applicable.</paratext>
</item>-
<item>-
<paratext>
Repeat steps
<xref xrefid="ref3"/>
. through
<xref xrefid="ref4"/>.
for remaining wheel.</paratext>
</item>-
<item>
<paratext>Apply thick coat of grease to wheel shafts.</paratext>
</item>-
<item>
<paratext>Remove gloves and then goggles.</paratext>
</item>
Dim xmlDoc As New DOMDocument
Dim n As IXMLDOMNode
'ProcSteps
For Each n In xmlDoc.selectNodes("//procsteps/seqlist/item/paratext")
Debug.Print strSYSCOM, n.hasChildNodes, n.Text
If n.hasChildNodes = False Then ' does this step reference other steps? If so, we don't need to process it.
If HasNumber(n.Text) Then
rsSteps.AddNew
rsSteps!MRC_ID = lngMRCID
rsSteps!txtStep = n.Text
rsSteps.Update
End If
End If
Next
End If
所以基本上我要确定的是paratext标签中是否存在外部参照标签。如果他们这样做,那么我不想处理paratext标签。而且,我需要尽可能高效地完成这项工作,因为我需要处理数千个XML文档。
当我打印如上所示的n.text时,我得到了
重复步骤。通过。留下轮子。
所以在我看来,xref不是paratext的子节点。事实上,我还没有遇到过haschildnodes错误的情况。那么,我错过了什么? 大卫
答案 0 :(得分:1)
子节点不是子元素。每个元素的文本值也被认为是#34;节点&#34;。
为什么不简单地使用XPATH来执行此操作?
Sub foo()
Dim xml_string As String
Dim n As Object 'IXMLDomNode
Dim c as Object 'IXMLDomNode
Dim nodes As Object 'IXMLDomNodeList
Dim xmlDoc As Object 'MSXML2.DomDocument
xml_string = "<paratext>Repeat steps" & _
"<xref xrefid='ref3'/>" & _
" .through" & _
"<xref xrefid='ref4'/>." & _
" for remaining wheel.</paratext>"
Set xmlDoc = CreateObject("MSXML2.DomDocument")
xmlDoc.LoadXML xml_string
Set nodes = xmlDoc.SelectNodes("//paratext")
For Each n In nodes
If n.SelectNodes("//xref") Is Nothing Then
'Process this PARATEXT node
MsgBox "process!"
Else
'There ARE child nodes of /xref tagname, so skip this node
'do nothing
MsgBox "/xref child nodes exist, not processed!" & vbCrLf & vbCrLf & n.XML
End If
Next
End Sub
注意,如果xpath参数指定的节点不存在:
Set nodes = xmlDoc.SelectNodes("//paratext/Hulk_Hogan")
For / Each
循环将跳过,因为nodes
NodeList将是一个空集合。您甚至可以通过nodes.Length
进行测试(如果需要),当没有匹配的节点时,0
将返回{{1}}值。