DEV Community

Barret Blake
Barret Blake

Posted on • Originally published at barretblake.dev on

Function Friday – Xpath

Power Automate doesn’t give you any built-in methods for editing XML content, and that’s fine. XML is a devil-spawned file format that should die thousands of deaths and never see the light of day again. But, if you’re forced to use XML and need the ability to search and parse that XML in your flows, then Power Automate provides you a means for doing that search: XPath.

The format is simple:

xpath(<XML>, <XPATH>)
Enter fullscreen mode Exit fullscreen mode

The parameter is the XML text to search, be it literal or a variable. And the parameter is the pattern to search for. The return value can be a bit of a pain. If only a single result occurs, you get that XML node result. If multiple matches are found, then you get an array of results. So your code will have to figure out whether you are dealing with a single result or an array.

Take, for instance, the following XML data stored in a string variable named jedi:

<?xml version="1.0"?>
<jedi>
  <knights>
    <knight>
      <name>Mace Windu</name>
    </knight>
    <knight>
      <name>Obiwan Kenobi</name>
    </knight>
    <knight>
      <name>Anakin Skywalker</name>
    </knight>
  </knight>
  <apprentices>
    <apprentice>
      <name>Ahsoka Tano</name>
    </apprentice>
  </apprentices>
</jedi>
Enter fullscreen mode Exit fullscreen mode

The following XPath query will return an array:

xpath(jedi, '/jedi/knights/knight/name') // returns ['<name>Mace Windu</name>','<name>Obiwan Kenobi</name>','<name>Anakin Skywalker</name>']
Enter fullscreen mode Exit fullscreen mode

While the following XPath queries will return a single value:

xpath(jedi, '/jedi/apprentices/apprentice/name') // returns '<name>Ahsoka Tano</name>'
xpath(jedi, '/jedi/knights/knight/name[first()]') // returns '<name>Mace Windu</name>'
Enter fullscreen mode Exit fullscreen mode

If your XPath query returns a data value instead of a node (for example, if you search for the value of the first name node instead of the node itself), then your return result can be any value and won’t necessarily be a valid XML node. And, of course, if no results are found, your return value will be null.

So, the code you implement to process the result of your search must be able to handle all four of these use cases, making the manipulation of XML a pain to work with in Power Automate. You can do it. But if you have another option, I’d recommend you opt for that instead.

The post Function Friday – Xpath first appeared on Barret Codes.

Top comments (0)