How to find and replace a text in xml file

조회 수: 12 (최근 30일)
Husam Kaid
Husam Kaid 2019년 11월 20일
편집: Deepak 2025년 1월 6일
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