这看起来应该很容易,但并不像预期的那样有效。首先,我将发布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标记中是否存在xref标记。如果是这样的话,那么我就不想处理paratext标记。而且,我需要尽可能高效地完成这一任务,因为我需要处理数千个XML文档。
如上面所示,当我打印n.text时,我得到
重复步骤。穿过。剩下的轮子。
因此,在我看来,xref不是paratext的子节点。事实上,我还没有遇到过这样一种情况,那就是有孩子节点是错误的。那我错过了什么?大卫
发布于 2015-02-23 17:47:39
子节点不是子元素。每个元素的文本值也被认为是“节点”。
为什么不简单地使用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值。
https://stackoverflow.com/questions/28679098
复制相似问题