MATLAB Answers

How to change a value in a XML-File?

42 views (last 30 days)
Moritz on 2 Oct 2013
Commented: Alessandro on 2 Oct 2013
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?

Answers (1)

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
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;
inStream = org.xml.sax.InputSource();
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
Alessandro on 2 Oct 2013
Ok sorry I thought you wannt to change the node. That it is much more simplier:
Doc.getElementsByTagName('chargingStation').item(0).setAttribute('startPos','55') Doc.getElementsByTagName('chargingStation').item(0).setAttribute('endPos','75')

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!