How to modify an XML attribute value using Matlab?

In the following example, I demonstrate how to modify an XML attribute value in a particular XML node using XPath in MATLAB. XPath stands for XML Path Language and is a query language for selecting nodes in an XML document. The XPath language is based on a tree representation of the XML document.

Let’s consider the following sample XML file

<?xml version="1.0" encoding="utf-8"?>
    <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"/>

I am going to select the chargingStation node which id has the value of ChrgStn1. The XPath in this case is xml/chargingStation[@id="ChrgStn1"]. The full code in MATLAB would be:

import javax.xml.xpath.*

factory = XPathFactory.newInstance;
xpath = factory.newXPath;

expression = xpath.compile('xml/chargingStation[@id="ChrgStn1"]');
chargingStation = expression.evaluate(fXML, XPathConstants.NODE); 

if ~isempty(chargingStation)
     chargingStation.setAttribute('startPos', '45')        

xmlwrite('SampleXMLOut.xml', fXML);

If you need to select multiple nodes, you shall change the XPathConstants.NODE to XPathConstants.NODESET.