简体   繁体   中英

Modify an XML file with XPath in MATLAB

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.

Seems that you're modifying only the XML document object in memory. Try to save the object back to XML file at the end. Something like this maybe* :

Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("myXMLfile.xml"));
Source input = new DOMSource(myDocument);

transformer.transform(input, output);

*) I'm not a Java guy, snippet taken from this thread : How to save parsed and changed DOM document in xml file?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM