En el siguiente ejemplo, demuestro cómo modificar el valor de un atributo XML en un nodo XML concreto utilizando XPath en MATLAB. XPath significa XML Path Language y es un lenguaje de consulta para seleccionar nodos en un documento XML. El lenguaje XPath se basa en una representación de árbol del documento XML.
Consideremos el siguiente archivo XML de ejemplo
<?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>
Voy a seleccionar el nodo chargingStation
cuyo id tiene el valor de ChrgStn1
. El XPath
en este caso es xml/chargingStation[@id="ChrgStn1"]
. El código completo en MATLAB sería:
import javax.xml.xpath.* fXML=xmlread('SampleXML.xml'); 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') end xmlwrite('SampleXMLOut.xml', fXML);
Si necesita seleccionar varios nodos, deberá cambiar XPathConstants.NODE
por XPathConstants.NODESET
.