如果不存在具有特定值的属性,如何创建该属性-VBA

时间:2018-11-06 12:40:37

标签: excel vba excel-vba

对不起,我的英语不好,但是我会尽力描述我的问题。我在VBA中有一个代码。在这里:

Sub TestXML()
Dim doc As New DOMDocument
    Const filePath As String = "D:\Test3.xml"
    Dim isLoaded As Boolean

    isLoaded = doc.Load(filePath)

    If isLoaded Then
        Dim oAttributes As MSXML2.IXMLDOMNodeList
        Set oAttributes = doc.getElementsByTagName("Operation")

        Dim attr As MSXML2.IXMLDOMAttribute
        Dim node As MSXML2.IXMLDOMElement
        Dim tdate As String
        tdate = Format(Now(), "yyyy-mm-dd")
        For Each node In oAttributes
            For Each attr In node.Attributes
                If attr.Name = "Client" Then
                 If attr.Value <> "UL" Then
                    attr.Value = "UL"
                    End If
                ElseIf attr.Name = "Date" Then
                    If attr.Value <> "tdate" Then
                    attr.Value = tdate
                End If
                End If
            Next attr
        Next node

        doc.Save filePath

    End If
End Sub

问题是-仅当元素“操作”不存在时,如何才能为其创建属性“客户端”,其值为“ UL”? 这是我使用的.xml文件示例:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
    <Operations>
        <Operation Date="2018-11-06" Client="UL"/>
        <Operation Date="2018-11-06" Client="UL"/>
        <Operation Date="2018-11-06"/>
    </Operations>
</Document>

谢谢!

1 个答案:

答案 0 :(得分:2)

尝试读取属性节点(如果不存在)创建它:

For Each node In oAttributes

    If (node.getAttributeNode("Client") Is Nothing) Then
        '// add missing attrib
        node.setAttribute "Client", "UL"
    End If

您当前的代码似乎希望所有元素都具有Client = UL,以简单地完成此操作:

For Each node In oAttributes
    node.setAttribute "Client", "UL"
Next node

将根据需要覆盖或创建该属性。