How to change a value in a XML-File?

16 views (last 30 days)
Moritz
Moritz on 2 Oct 2013
Commented: Robert Ungi on 3 Jan 2022
Hello,
i have this XML-code
<busStop id="BusStop0" lane="1to2_0" startPos="20" endPos="30"/>
<busStop id="BusStop1" lane="1to2_0" startPos="70" endPos="80"/>
<chargingStation id="ChrgStn1" lane="1to2_0" startPos="20" endPos="30" chrgPower="220"/>
I want to change the value in "chargingStation" for "startPos" and for "endPos".
How do i write in MatLab?
Thanks!!!

Answers (1)

Alessandro
Alessandro on 2 Oct 2013
Edited: Alessandro on 2 Oct 2013
If I understand you right and you use the java node structure for matlab than you could use this function to replace the node:
%Function to replace a w3c node
function xmlreplacenode(node1,nodenew)
parent = node1.getParentNode;
node1.getParentNode.removeChild(xmlnode);%Delete the node
parent.appendChild(nodenew);
If not you should first parse the document with:
xDoc = xmlread(handles.tmpverzeichn);
You still need a function to generate a new node from a string maybe. For that you can try this:
%input doc is java org.w3c.dom Document
%str is a xml string
function node = parsestr2node(doc,str)
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.Node;
import java.io.*;
inStream = org.xml.sax.InputSource();
inStream.setCharacterStream(java.io.StringReader(str));
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
tmpdoc = docBuilder.parse (inStream);
node = doc.importNode(tmpdoc.getChildNodes.item(0),true);
If it doesn t work maybe you need some java files
  4 Comments
Robert Ungi
Robert Ungi on 3 Jan 2022
@Heinke W this might help:
% <?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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!