This is similar to this question: XSLT-1.0: How to insert an element at a specific position with respect to the parent element, but the answer there doesn't cover the case where tag3
is missing in the input XML
I want to insert or update a tag (say tag4) in the an XML document that looks like the following, except that tag1, tag2, tag3, tag4 and tag5 are all optional.
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="d" />
<tag5 value="e" />
</Begin>
I.e. the following are sample inputs and outputs
Input:
<Begin>
</Begin>
Output:
<Begin>
<tag4 value="updated" />
</Begin>
Input:
<Begin>
<tag4 value="d" />
</Begin>
Output:
<Begin>
<tag4 value="updated" />
</Begin>
Input:
<Begin>
<tag1 value="a" />
<tag5 value="e" />
</Begin>
Output:
<Begin>
<tag1 value="a" />
<tag4 value="updated" />
<tag5 value="e" />
</Begin>
Input:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag5 value="e" />
</Begin>
Output:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag4 value="updated" />
<tag5 value="e" />
</Begin>
Input:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag5 value="e" />
</Begin>
Output:
<Begin>
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="updated" />
<tag5 value="e" />
</Begin>
UPDATE
I also want to be able to preserve any attributes that may already be present on the Begin or tag4 element, e.g.:
Input:
<Begin someAttribute="someValue">
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="d" someOtherAttribute="someOtherValue" />
<tag5 value="e" />
</Begin>
Output:
<Begin someAttribute="someValue">
<tag1 value="a" />
<tag2 value="b" />
<tag3 value="c" />
<tag4 value="updated" someOtherAttribute="someOtherValue" />
<tag5 value="e" />
</Begin>
tag4
's attributes and then override thevalue
attribute, or copy all its attributes exceptvalue
. For theBegin
element, you can simply copy all its attributes before any of its children (or together with the first batch of its children).. – michael.hor257k