How to find and replace a text in xml file

12 views (last 30 days)
Husam Kaid
Husam Kaid on 20 Nov 2019
Edited: Deepak on 6 Jan 2025
In an xml file I want to change the name "Information" into "Data", in other word I need to find "Information" in an original xml and replace it by "Data". Could you help me.
original xml
*************
<Information>
<Model_name>1M1R.xml</Model_name>
<Type>1</Type>
</Information>
*************
Wanted xml
<Data>
<Model_name>1M1R.xml</Model_name>
<Type>1</Type>
</Data>

Answers (1)

Deepak
Deepak on 6 Jan 2025
Edited: Deepak on 6 Jan 2025
To modify an XML file in MATLAB, first use "xmlread" to load the XML file into a Document Object Model (DOM) object. Then, access the root element using "getDocumentElement()". If the tag name of root element is "Information", create a new element named "Data" and transfer all child nodes from the old element to the new one. Finally, use "xmlwrite" to save the modified XML document to a new file.
Here is the sample MATLAB code to achieve the same:
% Read the original XML file
xmlFileName = 'filename.xml';
xmlDoc = xmlread(xmlFileName);
% Get the root element
rootElement = xmlDoc.getDocumentElement();
% Check if the root element is "Information" and change it to "Data"
if strcmp(rootElement.getTagName(), 'Information')
% Create a new element with the name "Data"
newElement = xmlDoc.createElement('Data');
% Move all child nodes from the old element to the new element
while rootElement.hasChildNodes()
newElement.appendChild(rootElement.getFirstChild());
end
% Replace the old root element with the new one
xmlDoc.replaceChild(newElement, rootElement);
end
% Write the modified XML back to a file
xmlwrite('modifiedfile.xml', xmlDoc);
Please find attached documentation of functions used for reference:
I hope this assists in resolving the issue.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!