Macro VBA to update information in xml file

Vasilchyk Vladik

New Member
Joined
Jan 24, 2023
Messages
7
Office Version
  1. 365
  2. 2021
Platform
  1. Windows
Good day

In general, such a question.
There is an excel file with fields

IDNamePrice
101Pos#110
102Pos#220

and there is an xml file of this format

XML:
<offer available="true" id="101">
<price>10</price>
<currencyId>UAH</currencyId>
<categoryId>91456</categoryId>
<name>Товар №1</name>
<description><![CDATA[
<p>AAAAA.</p>]]></description>
<vendorCode>90/5</vendorCode>
<stock_quantity>1</stock_quantity>
</offer>

The task is that when you press a button in Excel from the desired line, focusing on the product id, information about the updated price is taken and the price in the xml file is updated with a reference to the product id.

That is, I change the price in Excel for 1 product to 12, and the second to 9, and press the macro start button. The price in the required xml file changes according to the principle for the product with id 101, the value in the <price></price> field changes from 10 to 12, and from 20 to 9 from id 102. Nothing else in this file changes.

Thanks for answers
And sorry for my bad english
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
The following code assumes that the worksheet containing the data is the active sheet. And it also assumes that your XML file contains a root element. The code loops through each row, starting with the second row, and updates the price for the corresponding ID in the specified file.. Change the path and filename for the specified file accordingly. The code should be place in a regular module (Visual Basic Editor or Alt+F11 >> Insert >> Module).

VBA Code:
Option Explicit

Sub UpdateXmlFile()

    Dim xmlDoc As Object
    Dim xmlNodeList As Object
    Dim xmlNode As Object
    Dim pathAndFilename As String
    Dim theID As String
    Dim thePrice As String
    Dim recordsEditedCount As Long
    Dim lastRow As Long
    Dim rowIndex As Long
  
    pathAndFilename = "c:\users\domta\desktop\sample.xml" 'change the path and filename accordingly
  
    Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
  
    If Not xmlDoc.Load(pathAndFilename) Then
        With xmlDoc
            MsgBox "Error " & .parseError.ErrorCode & ": " & .parseError.reason, vbExclamation, "Error"
        End With
        Exit Sub
    End If
  
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
  
    recordsEditedCount = 0
    For rowIndex = 2 To lastRow
        theID = Cells(rowIndex, "A").Value
        thePrice = Cells(rowIndex, "C").Value
        Set xmlNode = xmlDoc.SelectSingleNode("//offer[@id='" & theID & "']/price") 'assumes a root element, hence the double front slash ( // )
        If Not xmlNode Is Nothing Then
            xmlNode.Text = thePrice
            recordsEditedCount = recordsEditedCount + 1
        End If
    Next rowIndex
  
    If recordsEditedCount > 0 Then
        xmlDoc.Save pathAndFilename
    End If
  
    MsgBox "Number of records edited: " & recordsEditedCount
  
    Set xmlDoc = Nothing
    Set xmlNodeList = Nothing
    Set xmlNode = Nothing

  
End Sub

Hope this helps!
 
Upvote 0

Good afternoon Domenic​

Thanks for your decision. Unfortunately it shows this error on startup.

Error -1 many numbers DTD prohibited

Скриншот 26-01-2023 080804.jpg
 
Upvote 0
My table has changed a bit. I uploaded the table itself and the output file to change in the archive Update_xml_xls.zip

The Avaible string updates the value to
XML:
available=" "
, Stock in
XML:
<stock_quantity> </stock_quantity>

Thanks a lot for your help
 
Upvote 0
Sorry, but I don't download files as a rule, so I haven't looked at them. However, if you're saying that your XML file now includes another element, such as stock_quantity, then it's fine, the code should still work. With regards to your error, try the following code instead...

VBA Code:
Option Explicit

Sub UpdateXmlFile()

    Dim xmlDoc As Object
    Dim xmlNodeList As Object
    Dim xmlNode As Object
    Dim pathAndFilename As String
    Dim theID As String
    Dim thePrice As String
    Dim recordsEditedCount As Long
    Dim lastRow As Long
    Dim rowIndex As Long
 
    pathAndFilename = "c:\users\domta\desktop\sample.xml" 'change the path and filename accordingly
 
    Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
 
    With xmlDoc
        'Wait for the document to load completely
        .async = False
        'Allow the document to include a DTD
        .SetProperty "ProhibitDTD", False
        'Don't validate the document against a DTD or schema
        .validateOnParse = False
    End With
    
    If Not xmlDoc.Load(pathAndFilename) Then
        With xmlDoc
            MsgBox "Error " & .parseError.ErrorCode & ": " & .parseError.reason, vbExclamation, "Error"
        End With
        Exit Sub
    End If
 
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
 
    recordsEditedCount = 0
    For rowIndex = 2 To lastRow
        theID = Cells(rowIndex, "A").Value
        thePrice = Cells(rowIndex, "C").Value
        Set xmlNode = xmlDoc.SelectSingleNode("//offer[@id='" & theID & "']/price") 'assumes a root element, hence the double front slash ( // )
        If Not xmlNode Is Nothing Then
            xmlNode.Text = thePrice
            recordsEditedCount = recordsEditedCount + 1
        End If
    Next rowIndex
 
    If recordsEditedCount > 0 Then
        xmlDoc.Save pathAndFilename
    End If
 
    MsgBox "Number of records edited: " & recordsEditedCount
 
    Set xmlDoc = Nothing
    Set xmlNodeList = Nothing
    Set xmlNode = Nothing

 
End Sub

Hope this helps!
 
Upvote 0

Good afternoon Domenic​

Thanks for your decision.
Unfortunately for some reason the xml file is not updated.
After launch, a window is displayed "Number of record edited: 0"

Скриншот 27-01-2023 063325.jpg
 
Upvote 0
It suggests that it didn't find any of those ID's and/or element named price in the specified XML file.

Can you post the exact code that you're using?

Also, can you post a small sample of the exact XML file you're using, including the XML declaration and root element?

Note that I'm logging off for the evening, but I'll look at this as soon as I get a chance.

Cheers!
 
Upvote 0
Thank you. Somehow figured it out. The price is being updated.
Can you tell me what to change in the code to update other fields from excel in xml
Small piece of code xml

XML:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog date="2023-01-09 12:00">
    <shop>
        <name></name>
        <company>А</company>
        <url>https://a.com.ua</url>
        <currencies>
            <currency id="UAH" rate="1"/>
        </currencies>
        <categories>
            <category id="6300">Cat1</category>
        </categories>
        <offers>
            
            <offer available="true" id="101">
                <price>11111</price>
                <currencyId>UAH</currencyId>
                <categoryId>6300</categoryId>
                <name>1</name>
                <description><![CDATA[
<p>AAAAA.</p>]]></description>
                <vendorCode>90/5</vendorCode>
                <stock_quantity>10</stock_quantity>
            </offer>
            
        </offers>
    </shop>
</yml_catalog>
 
Upvote 0
I think I figured out how to pull the value from other elements.
Please tell me how to change the value here
XML:
available="true"
value between quotes
 
Upvote 0
Try the following code . . .

VBA Code:
Option Explicit

Sub UpdateXmlFile()

    Dim xmlDoc As Object
    Dim xmlNodeList As Object
    Dim xmlNode As Object
    Dim pathAndFilename As String
    Dim theID As String
    Dim thePrice As String
    Dim available As String
    Dim stockQuantity As Long
    Dim recordsEditedCount As Long
    Dim lastRow As Long
    Dim rowIndex As Long
 
    pathAndFilename = "c:\users\domta\desktop\sample.xml" 'change the path and filename accordingly
 
    Set xmlDoc = CreateObject("MSXML2.DOMDocument.6.0")
 
    With xmlDoc
        'Wait for the document to load completely
        .async = False
        'Allow the document to include a DTD
        .SetProperty "ProhibitDTD", False
        'Don't validate the document against a DTD or schema
        .validateOnParse = False
    End With
    
    If Not xmlDoc.Load(pathAndFilename) Then
        With xmlDoc
            MsgBox "Error " & .parseError.ErrorCode & ": " & .parseError.reason, vbExclamation, "Error"
        End With
        Exit Sub
    End If
 
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
 
    recordsEditedCount = 0
    For rowIndex = 2 To lastRow
        theID = Cells(rowIndex, "A").Value
        thePrice = Cells(rowIndex, "C").Value
        available = Cells(rowIndex, "D").Value
        stockQuantity = Cells(rowIndex, "E").Value
        Set xmlNode = xmlDoc.SelectSingleNode("//offer[@id='" & theID & "']")
        If Not xmlNode Is Nothing Then
            With xmlNode
                .SelectSingleNode("price").Text = thePrice
                .Attributes.getNamedItem("available").Text = LCase(available)
                .SelectSingleNode("stock_quantity").Text = stockQuantity
            End With
            recordsEditedCount = recordsEditedCount + 1
        End If
    Next rowIndex
 
    If recordsEditedCount > 0 Then
        xmlDoc.Save pathAndFilename
    End If
 
    MsgBox "Number of records edited: " & recordsEditedCount
 
    Set xmlDoc = Nothing
    Set xmlNodeList = Nothing
    Set xmlNode = Nothing

 
End Sub

Hope this helps!
 
Upvote 0
Solution

Forum statistics

Threads
1,223,905
Messages
6,175,297
Members
452,633
Latest member
DougMo

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top