How to find and replace a text in xml file

3 ビュー (過去 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 Center および File ExchangeStructured 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