【问题标题】:How to get node values in XML using VBScript?如何使用 VBScript 获取 XML 中的节点值?
【发布时间】:2017-03-05 00:09:00
【问题描述】:

我正在尝试将所有重复的节点保存到一个数组中以用于我的 QTP 自动化。

当我们使用下面的代码时,我们会得到 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

上面的代码将该节点的值存储到 Array 而不是节点本身。你能帮我如何将节点存储到数组而不是节点值

代码显示的输出:

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

预期输出:

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

【问题讨论】:

    标签: xml dom vbscript qtp


    【解决方案1】:

    NodeValue 属性为您提供节点的。您正在寻找的是节点的 path。 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
    

    不过,上面的代码只是一个示例,还有很大的改进空间。例如,它不检查兄弟姐妹是否实际上具有相同的节点名称。

    【讨论】:

    • 谢谢安斯加尔。将对此进行调查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多