2017-03-05 102 views
0

我試圖將所有重複節點保存到我的QTP自動化陣列中。如何使用VBScript獲取XML中的節點值?

當我們使用下面的代碼時,我們得到了XML中存在的所有重複節點。 例子:

strXmlPCoverage = /cts:InsuranceClaim/cts:MedicalClaim 

Set nodes = xmlDoc.SelectNodes(strXmlPCoverage) 
PathLength = nodes.Length 

比方說,PathLength返回存在於XML作爲重複標記爲「6」的標籤。

/cts:InsuranceClaim/cts:MedicalClaim[0] 
/cts:InsuranceClaim/cts:MedicalClaim[1] 
/cts:InsuranceClaim/cts:MedicalClaim[2] 
/cts:InsuranceClaim/cts:MedicalClaim[3] 
/cts:InsuranceClaim/cts:MedicalClaim[4] 
/cts:InsuranceClaim/cts:MedicalClaim[5]

現在我想保存所有這6個不同的路徑到數組。我無法識別顯示存儲在nodes中的值的屬性。

Set nodes = xmlDoc.SelectNodes(strXmlPCoverage) 
PathLength = nodes.Length 
For Each NodeItem In nodes 
    ArrAllNodes(i) = NodeItem.nodeValue 
Next 

上面的代碼將該節點的值存儲到數組而不是節點本身。能否請你幫我如何節點存儲陣列,而不是節點值由代碼顯示

輸出:

ArrAllNodes(0) = abc 
ArrAllNodes(1) = xyz 
... 

產出預期:

ArrAllNodes(0) = /cts:InsuranceClaim/cts:MedicalClaim[0] 
ArrAllNodes(1) = /cts:InsuranceClaim/cts:MedicalClaim[1] 
... 

回答

1

NodeValue屬性給你一個節點的。你要找的是節點的路徑。 DOM對象沒有提供該信息的方法/屬性,所以您需要通過在DOM樹中向上遍歷(通過ParentNode屬性)自行確定路徑。

像這樣的東西可能會給你一個起點:

Function HasSiblings(n) 
    HasSiblings = (TypeName(n.PreviousSibling) = "IXMLDOMElement") Or _ 
        (TypeName(n.NextSibling) = "IXMLDOMElement") 
End Function 

Function GetIndex(n) 
    If n.PreviousSibling Is Nothing Then 
     GetIndex = 0 
    Else 
     GetIndex = GetIndex(n.PreviousSibling) + 1 
    End If 
End Function 

Function GetPath(n) 
    path = "\" & n.NodeName 

    'add index if node has siblings 
    If HasSiblings(n) Then 
     path = path & "[" & GetIndex(n) & "]" 
    End If 

    'add parent path if current node is not the document element 
    If TypeName(n.ParentNode) = "IXMLDOMElement" Then 
     path = GetPath(n.ParentNode) & path 
    End If 

    GetPath = path 
End Function 

上面的代碼就是用大量的提升空間的樣本,雖然。例如,它不檢查兄弟節點是否實際上具有相同的節點名稱。

+0

謝謝Ansgar。將研究這一點。 –