1

I have an example where I need to update an XML node based on an XPath. SimpleXMLElement makes this easy enough by using an XPath to grab the node and then update its value in a pass-by-reference format.

However, this doesn't work at all if the node doesn't actually exist that needs to be updated. Are there any simple ways to automatically generate the XML that matches the XPath if it doesn't exist?

An example:

<example>
   <childNode1>green</childNode1>
</example>

Given the XML, I could easily run the xpath command to get the <childNode1> by loading up the xml into a SimpleXMLElement and then running $xml->xpath("example/childNode1");. I could then set the value of the returned SimpleXMLElement to something new and then save the xml.

However, if I needed to set something like <childNode2> the $xml->xpath("example/childNode2") would return nothing and it wouldn't be possible to set the value or confirm that the XML was built.

Is iterating through the XPath and parsing its values the only way to confirm that each child node exists and then build them out as it goes or is there a better way to generate the necessary XPath?

Marcus Rickert
  • 4,138
  • 3
  • 24
  • 29
sailboatlie
  • 346
  • 1
  • 6
  • 18
  • 1
    I answered something like that for JavaScript some time ago: http://stackoverflow.com/a/26296087/2265374 – ThW Oct 24 '14 at 09:31

1 Answers1

2

XPath is a query language used for selecting nodes in an XML structure and optionally computing values based on the contents of the XML. It does not possess functions that enable the editing of the XML or automagic node creation.

PHP's SimpleXML and DOM both have XPath implementations and allow the creation or updating of XML structures; I assume you know about them since you talk about editing nodes (I can give examples if you don't). To perform the kind of node additions that you are proposing, you would need to ascertain whether the node existed (e.g. if the xpath query for example/node1 returned a node, but example/node2 returned nothing), create a new node, and add it to the XML tree. For long xpaths, e.g. example/apple/blueberry/canola/date/emblem/node1, you would indeed have to parse the path and check which elements did exist, and add those that did not.

XQuery, a more powerful, fully-featured XML query language of which XPath 2 and XPath are part, will have the ability to transform XML. XQuery is in active development, but unfortunately the current implementations (as of late 2014) lack the ability to update XML. Watch this space though!

i alarmed alien
  • 9,412
  • 3
  • 27
  • 40