Skip to content

Add an element

This article explains how to add an element to an existing XML file or XML data.

This article uses the “Insert XML element” action.

Details of the “Insert XML element” action

Section titled “Details of the “Insert XML element” action”

The action has the following parameters.

Parameter Value
XML document The target XML data (must be an XML node object)
XPath query Specify, in XPath format, the parent element to insert the element into
XML element to insert The XML data to insert

action

Add the sample flow by copying and pasting

Section titled “Add the sample flow by copying and pasting”

As a sample, this article uses a flow that saves XML data to a file, reads the data back, and adds an element to it.

Copy the following code and paste it into the Power Automate Desktop flow designer to add the actions.

SET FilePath TO $'''C:\\Users\\Public\\Documents\\sample.xml'''
XML.WriteXmlToFile.WriteToFileFormatted File: FilePath Xml: $'''<sample><data><content>This is test data</content></data></sample>''' Encoding: XML.FileEncoding.UTF8 Indentation: 2
XML.ReadFromFile File: FilePath Encoding: XML.FileEncoding.UTF8 XmlDocument=> XmlDocument
XML.InsertElement Document: XmlDocument XPathQuery: $'''/sample/data''' Element: $'''<insert>Content added from PAD</insert>'''

Before the flow runs, the XML looks like this.

<sample>
<data>
<content>This is test data</content>
</data>
</sample>

After the flow runs, the content of the XmlDocument variable changes as follows.

<sample>
<data>
<content>This is test data</content>
<insert>Content added from PAD</insert>
</data>
</sample>
  1. In “Search actions”, type “Insert XML element”.

  2. Set the parameters as follows.

    Parameter Value
    XML document %XmlDocument%
    XPath query /sample/data
    XML element to insert <insert>Content added from PAD</insert>
  3. When you run the flow, the specified element is added to the target XML data.

This action changes only the content of the variable (the XML node); the original XML file isn’t updated. To save the change to the file, write it with the “Write XML to file” action afterward.

An error occurs if the XPath syntax is wrong or if you specify an invalid XPath.

Even if the syntax is correct, an error occurs if the specified XPath doesn’t return an element (for example, when no element matches).

An error also occurs if inserting the element itself fails.

We recommend adding error handling with an “On block error” block.