2015-02-23 68 views
0

這似乎應該很容易,但它不能按預期工作。首先,我將發佈XML,然後發佈我擁有的VBA。不幸的是,我無法發佈整個XML文件。VBA IXMLDOMNode.hasChildNodes對我來說工作不正常

-<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錯誤的情況。那麼,我錯過了什麼? David

回答

0

子節點不是孩子元素。每個元素的文本值也被認爲是「節點」。

爲什麼不簡單地使用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節點列表將是一個空的集合。您甚至可以通過執行nodes.Length來測試(如果您需要),當沒有匹配的節點時,將返回0值。

相關問題