Skip to content

How do I replace existing keys/values in an XML document

This example demonstrates the approaches to replace existing keys/values in an XML document and returns the result within the context of an automated test in execution.

Solution:

Approach 1:

In this example, you store the XML in a variable and using the "xmlReplaceNodesByPaths" command, the path/key pair for an existing path in the document overwrites the existing document value with the new key i.e "income" key is replaced with "salary".

# Command Target Value
store the xml
1 store <?xml version="1.0" encoding="UTF-8"?>

<insuranceData>

  <insurance category="valid">

      <age>45</age>

      <income>55000</income>

      <zipcode>90001</zipcode>

      <result>You are eligible for a subsidy.</result>

  </insurance>

  <insurance category="valid">

      <age>64</age>

      <income>25000</income>

      <zipcode>14301</zipcode>

      <result>You are eligible for a subsidy.</result>

  </insurance>

  <insurance category="invalid">

      <age>15</age>

      <income>25000</income>

      <zipcode>08857</zipcode>

      <result>Combinations of inputs provided out of scope for the calculator.</result>

  </insurance>

</insuranceData>
XML
Replace existing keys in an XML document
2 xmlReplaceNodesByPaths ${XML} || {/insuranceData//insurance[1]/income,income}||{/insuranceData//insurance[1]/income,salary} Variable

Approach 2:

In this example, you store the XML in a variable and using the "xmlReplaceNodesByPaths" command, the path/key pair for an existing path in the document overwrites the existing document value with the new value i.e age value is replaced from "15" to "45".
# Command Target Value
store the xml
1 store<?xml version="1.0" encoding="UTF-8"?>

<insuranceData>

  <insurance category="valid">

      <age>45</age>

      <income>55000</income>

      <zipcode>90001</zipcode>

      <result>You are eligible for a subsidy.</result>

  </insurance>

  <insurance category="valid">

      <age>64</age>

      <income>25000</income>

      <zipcode>14301</zipcode>

      <result>You are eligible for a subsidy.</result>

  </insurance>

  <insurance category="invalid">

      <age>15</age>

      <income>25000</income>

      <zipcode>08857</zipcode>

      <result>Combinations of inputs provided out of scope for the calculator.</result>

  </insurance>

</insuranceData>
XML
To replace existing values in an XML document
2 xmlReplaceValuesByPaths ${XML} || {/insuranceData//insurance[3]//age,15} || {/insuranceData//insurance[3]//age,45} Variable

Tips, Tricks, Gotchas & Best Practices:  

  • The XML should be valid and encoded in "UTF-8" format.
  • You can use the xmlAssertPathExists command to check if the path is valid or invalid.
    The nodeValue should not be greater than existing nodes.


Feedback and Knowledge Base