Home » excel » excel – How to create an attribute with specific value if it doesn't exist – VBA

excel – How to create an attribute with specific value if it doesn't exist – VBA

Posted by: admin April 23, 2020 Leave a comment

Questions:

Sorry for my bad English, but i’ll try to describe my problem right. I have a code in VBA. Here it is:

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

Question is – How can i create attribute “Client” with value “UL” in element “Operation” only if it doesn’t exist?
Here is a .xml file example with which i working:

<?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>

Thanks!

How to&Answers:

Try to read the attribute node, if it does not exist create it:

For Each node In oAttributes

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

Your current code seems to want all elements to have Client=UL, to accomplish that simply:

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

Which will overwrite or create the attribute as needed.