Combining XML With the + Operator

You can use the + operator to combine XML elements. This can be useful when you want to create a new list of XML elements from XML elements returned from another expression. You can also use the + operator to add new XML to existing XML.

/* Declare an XML variable with a literal XML value. */
var xmlEmployees =
    <employees>
        <employee>
            <firstname>John</firstname>
            <lastname>Walton</lastname>
            <age>25</age>
        </employee>
        <employee>
            <firstname>Sue</firstname>
            <lastname>Day</lastname>
            <age>32</age>
        </employee>
        <employee>
            <firstname>Gladys</firstname>
            <lastname>Cravits</lastname>
            <age>53</age>
        </employee>
</employees>;

/* Collect the first and third <employee> nodes into a new XML snippet. */
var xmlSelectedEmployees = xmlEmployees..employee[0] + xmlEmployees..employee[2];

/* Add a new <employee> element to the list. */
var xmlCompleteList = xmlSelectedEmployees + <employee><firstname>Bruce</firstname><lastname>Wayne</lastname><age>36</age></employee>;

You might also find the appendChild function useful when combining XML elements. For more information, see appendChild function.

Related Topics

appendChild function