Mike the new guy
Mike the new guy

Reputation: 21

How do I replace two attribute values in a selected xml file?

I need to replace the values of "XXXXXX" and "YYYY". The replacements in quotes will always be the same. But the original values in the quotes will always be different. I'm very new to coding so any help would be appreciated.

<?xml version="1.0" encoding="utf-8"?>
<CellProgram>
  <CellConfiguration CellName="XXXXXX" PartName="YYYYY">

Upvotes: 1

Views: 2600

Answers (1)

RubberDuck
RubberDuck

Reputation: 12789

You need to add a reference to the Microsoft XML library to work with the XML DomDocument.

VBA Project References

Using this library, you will need to take the following steps.

  1. Load the document. (I've loaded it from a file, you can also load it from a string with the LoadXML method.)
  2. Get the list of elements named "CellConfiguration".
  3. For each CellConfiguration loop through the attributes of the node.
  4. Check the attribute name to see if/what it's value should be updated to and then update it appropriately.
  5. Save the document.

Here's what I came up with.

Public Sub test()

    Dim doc As New DOMDocument
    Const filePath As String = "C:\Users\x1ucjk2\Documents\test.xml"
    Dim isLoaded As Boolean

    isLoaded = doc.Load(filePath)

    If isLoaded Then
        Dim CellConfigurationList As MSXML2.IXMLDOMNodeList
        Set CellConfigurationList = doc.getElementsByTagName("CellConfiguration")

        Dim attr As MSXML2.IXMLDOMAttribute
        Dim node As MSXML2.IXMLDOMElement
        For Each node In CellConfigurationList
            For Each attr In node.Attributes
                If attr.Name = "CellName" Then
                    attr.Value = "Test"
                ElseIf attr.Name = "PartName" Then
                    attr.Value = "AuxCell"
                End If
            Next attr
        Next node

        doc.Save filePath

    End If

End Sub

Upvotes: 2

Related Questions