How to find and replace a text in xml file

12 次查看(过去 30 天)
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>

回答(1 个)

Deepak
Deepak 2025-1-6
编辑:Deepak 2025-1-6
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.

类别

Help CenterFile Exchange 中查找有关 Structured Data and XML Documents 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by