Change the value of a parameter in xml file using matlab

52 ビュー (過去 30 日間)
Zeynab Mousavikhamene
Zeynab Mousavikhamene 2019 年 9 月 26 日
回答済み: Robert Ungi 2022 年 1 月 3 日
I have xml file and want to change a value of a parameter inside it. The line that has that specific parameter is:
<variable id="MIG" value="3" description="Change in MIG" />
I want to change value from 3 to other number.
I found these functions to read and write xml file:
DOMnode = xmlread('parameter.xml');
xmlwrite('newparameter.xml',DOMnode);
but not sure how to change the value of variable called "MIG".

回答 (2 件)

Abhilash Padma
Abhilash Padma 2019 年 10 月 1 日
To change the value of a parameter in an element, along with xmlread and xmlwrite, we need to use getElementsByTagName and setAttribute methods. See the following code where I have changed the value of parameter “value”.
test.xml
<variable id="MIG" value="3" description="Change in MIG" />
xDoc=xmlread(fullfile(('test.xml')));
allListItems=xDoc.getElementsByTagName('variable');
thisListItem=allListItems.item(0);
thisListItem.setAttribute('value','20');

Robert Ungi
Robert Ungi 2022 年 1 月 3 日
A more general way to do so is
% <?xml version="1.0" encoding="utf-8"?>
% <xml>
% <busStop endPos="30" id="BusStop0" lane="1to2_0" startPos="20"/>
% <busStop endPos="80" id="BusStop1" lane="1to2_0" startPos="70"/>
% <chargingStation chrgPower="220" endPos="30" id="ChrgStn1" lane="1to2_0" startPos="45"/>
% </xml>
import javax.xml.xpath.*
factory = XPathFactory.newInstance;
import javax.script.ScriptContext;
xpath = factory.newXPath;
fXML=xmlread('SampleXML.xml');
expression = xpath.compile('xml/chargingStation[@id="ChrgStn1"]');
chargingStation = expression.evaluate(fXML, XPathConstants.NODESET);
for i=0:chargingStation.getLength-1
chargingStation.item(i).setAttribute('startPos', "45")
end
xmlwrite('SampleXMLOut.xml', fXML);
Adopted from The Wizzart.

カテゴリ

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