I'm trying to open and modify an XML file in MATLAB using XPath. Here the code I have written so far:
import javax.xml.xpath.*
doc = xmlread(which('myXMLfile.xml'));
factory = XPathFactory.newInstance();
xpath = factory.newXPath();
expr = xpath.compile('/data//parameter[@name=''MYPARAMETER'']/double');
nodeList = expr.evaluate(doc,XPathConstants.NODESET);
disp(char(nodeList.item(0).getFirstChild.getNodeValue))
nodeList.item(0).setNodeValue('0.03')
And my XML file :
<data>
...
<parameter name="MYPARAMETER">
<double>0.05</double>
</parameter>
...
The disp
line correctly display in the MATLAB command window the value, which here is 0.05
.
The script doesn't throw an error. However, the 0.03
value is not set in the XML file. What am I doing wrong and why is the value not written to the file with the setNodeValue
command?
EDIT
As proposed, it might not be saved because it is just modified in memory. I added the following lines to my code:
factory = javax.xml.transform.TransformerFactory.newInstance();
transformer = factory.newTransformer();
writer = java.io.StringWriter();
result = javax.xml.transform.stream.StreamResult(writer);
source = javax.xml.transform.dom.DOMSource(doc);
transformer.transform(source, result);
I'm getting no errors, but the XML file is still not modified.
Edit 2
import javax.xml.xpath.*
import javax.xml.transform.*
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
doc = xmlread(which('ImagingSensor.vpar'));
factory = XPathFactory.newInstance();
xpath = factory.newXPath();
expr = xpath.compile('/data//parameter[@name=''FOV'']/double');
nodeList = expr.evaluate(doc,XPathConstants.NODESET);
disp(char(nodeList.item(0).getFirstChild.getNodeValue))
nodeList.item(0).getFirstChild.setNodeValue('0.03')
With nodeList.item(0).getFirstChild.setNodeValue('0.03')
the value is correctly changed (but still not saved to file).
When using nodeList.item(0).setNodeValue('0.03')
, it didn't change the value correctly.