# Functions for Manipulating XML

When writing ECMAScript to manipulate XML, you have access to several member functions designed to make the task easier. This topic describes the functions available with ECMAScript.

The functions described in this topic are exposed by the four types provided with ECMAScript: XML, XMLList, Namespace, and XMLAttribute. For those functions that apply to multiple types, the function's specifics may differ slightly for each type. For more information on the four types, see Creating and Using XML Variables.

There may be cases when an element name conflicts with the name of a function listed in this topic. When that occurs, use syntax like that shown in the following example. In this example, the conflicting element name is preceding with a :: (double-colon).

    /*
     * Return the first <parent> element.
     * This avoids a conflict with the parent function.
     */
    var firstParent = xmlFamilies.kid.::parent[0];

## Functions Exposed by ECMAScript Types for XML

Many of the following functions are exposed by multiple types. For more information on the types themselves, see Creating and Using XML Variables.

Function | Description | Applies To
--- | --- | ---
xml.appendChild(newChild) | Inserts a new child node after the existing children of the XML value. | XML, XMLList
xml.attribute(attributeName) | Returns the value of the specified attribute as an XMLAttribute. | XML, XMLList
xml.attributes() | Returns a list of attributes for the specified element as an XMLAttribute array. | XML, XMLList
xml.child(childIndex) | Returns the XML at the 0-based ordinal position specified by childIndex. | XML, XMLList
xml.childIndex() | Returns the 0-based ordinal position of the XML value within its parent. | XML, XMLList
xml.children() | Returns a list of the element's children. | XML, XMLList
xml.comments([booleanToLookDeep]) | Returns a list of comments from xml's point in the document. | XML, XMLList
xml.copy() | Returns a copy of the specified element. | XML, XMLList
xml.cursor() | Returns an XmlCursor instance for the current element. | XML, XMLList
xml.document() | Returns xml as a document. | XML, XMLList
xml.getName() | Return the local name for xml. | XML, XMLAttribute
xml.getValue() | Returns the value (content) of xml. | XML, XMLList, XMLAttribute
xml.innerXML(newContent) | Replaces the entire contents of the XML value with new content. | XML, XMLList
xml.isComment() | Returns true if xml is an XML comment. | XML, XMLList
xml.isDocument() | Returns true if xml represents the XML document; otherwise, false. | XML, XMLList
xml.isProcessingInstruction() | Returns true if xml is an XML processing instruction. | XML, XMLList
xml.length | Returns the length of a list XML elements. | XML, XMLList
xml.namespaceURI() | Returns a string representing the namespace URI associated with xml. | XML, XMLList, XMLAttribute, Namespace
xml.namespaces() | Returns an array of Namespace objects that represents any xmlns attribute (with or without a prefix) declared in the entire XML document. | XML, XMLList
xml.parent() | Returns the parent of the element. | XML, XMLList, XMLAttribute
xml.prependChild(newChild) | Inserts a new child node before the existing children of the XML value. | XML, XMLList
xml.processingInstructions([booleanToLookDeep]) | Returns a list of all the XML processing instructions (PIs) from this element's point in the document. | XML, XMLList
xml.setValue(newValue) | Sets the value (content) of xml to newValue. | XML, XMLList
xml.tagName() | Returns the name of the element tag. | XML, XMLList
xml.text() | Returns a string containing the value of all XML properties of xml that are of type string. | XML, XMLList
xml.thisXML | Specifies the current XML, such as XML returned from an expression. | XML, XMLList
xml.toString() | Returns the element and its content as a string. | XML, XMLList, XMLAttribute, Namespace
xml.toXMLString() | Returns an XML encoded string representation of xml. | XML, XMLList
xml.xpath(xPathExpression) | Evaluates the XPath expression using the XML value as the context node. | XML, XMLList

Each of the functions listed in this topic is illustrated with an example based on the following XML variable.

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

## xml.appendChild(newChild)

Inserts a new child element (specified by newChild) after the existing children of xml.

The following example adds a <hobby> element to the end of the element assigned to xmlSue.

    var xmlSue = xmlEmployees..employee.(firstname == "Sue");
    xmlSue.appendChild(<hobby>snorkeling</hobby>);

## xml.attribute(attributeName)

Returns the value of attributeName as an XMLAttribute.

The following example returns a string containing Sue's ID number.

    var xmlEmployeeID = xmlEmployees.employees.employee.(firstname == "Sue").attribute("id");

Note that the attribute() function is an alternative to the @ operator. Because you may pass it a variable rather than a literal value, the attribute() function is useful when the attribute in question is unknown until run time.

For more information about the @ operator, see Accessing Attributes with the @ Operator.

## xml.attributes()

Returns a list of attributes for xml as an XMLAttribute array.

The following example returns the attributes for the <employee> element where the <name> value is "Sue"; its return value is "id".

    var suesAttributes = xmlEmployees..employee.(firstname == "Sue").attributes();

## xml.child(childIndex)

Returns the XML at the 0-based ordinal position specified by childIndex.

The second line of code in the following example returns an XML type containing the information about Sue.

    var secondEmployeeIndex = xmlEmployees..employee.(firstname == "Sue").childIndex();
    var secondEmployee = xmlEmployees.employees.child(secondEmployeeIndex);

## xml.childIndex()

Returns the ordinal position (within its parent) of xml.

The following example returns the index of the <employee> element where the <name> element value is "John". Returns "0".

    var johnIndex = xmlEmployees..employee.(firstname == "John").childIndex();

Note that when the expression to the left of childIndex returns multiple items, childIndex returns -1, as in the following example:

    var nameIndex = xmlEmployees..employee.name.childIndex();

## xml.children()

Returns an XMLList containing all of the children of xml.

The following example returns the child elements of the first employee element in xmlEmployees. It returns "John, Walton, 25".

    var xmlEmps = xmlEmployees..employee[0].children();

## xml.comments([booleanToLookDeep])

Returns a list of comments from xml's point in the document.

This method can take an optional argument (true or false) signaling to look deep. If no argument is specified, or if false is specified, only comments which are a sibling to xml are returned. Otherwise, all comments from this point down the entire depth of the tree are returned.

## xml.copy()

Returns a deep copy of xml.

The following example adds data about Gladys, a new employee, to a list that already includes John and Sue.

Result: The XML held by newEmployee is added to the list of employees.

    /* Create a new variable from data from the first employee in the list. */
    var newEmployee = xmlEmployees..employee[0].copy();
    /* Assigned new values to the copy. */
    newEmployee.@id = "555555555";
    newEmployee.firstname = "Gladys";
    newEmployee.lastname = "Cravits";
    newEmployee.age = "43";
    /* Append the copy to the list of employees. */
    xmlEmployees..employees += newEmployee;

## xml.cursor()

Returns an XmlCursor instance for xml.

For more information on the XmlCursor interface, see Navigating XML with Cursors.

## xml.document()

Returns xml as a document.

You can think of a "document" as the containing entity for xml. The document function is especially useful when your script is executing with the literalIsDocument environment variable set to false (the default).

For example, you could insert a new top-level element to the XML above with code such as this:

    xmlEmployees.document().volunteers = <volunteer/>;

The result would be the following:

    <employees>
        <employee id="111111111">
            <firstname>John</firstname>
            <lastname>Walton</lastname>
            <age>25</age>
        </employee>
        <employee id="222222222">
            <firstname>Sue</firstname>
            <lastname>Day</lastname>
            <age>32</age>
        </employee>
    </employees>
    <volunteers>
        <volunteer/>
    </volunteers>

## xml.getName()

Return the local name for xml.

## xml.getValue()

Returns the value (content) of xml.

## xml.isComment()

Returns true if xml is an XML comment.

## xml.isDocument()

Returns true if xml represents the XML document; otherwise, false.

When working with XML in script, you can specify an option to indicate whether the XML variable should represent the XML document or the XML's root element. That environment variable is literalIsDocument, as described in Setting Environment Attributes for XML in ECMAScript.

For example, consider the following assignment:

    var myXml = <name><first>Joe</first><last>Schmoe</last></name>;

With literalIsDocument set to false (the default), the code would look like this:

    var firstName = myXml.first;

With literalIsDocument set to true, code to retrieve the first name might look like this:

    var firstName = myXml.name.first;

The following would also return true:

    myXml.isDocument();

## xml.innerXML(newContent)

Replaces the entire contents of xml with newContent.

Note that this is not the same as reassigning the variable. In the example below, the root element represented by the variable (<employee>) remains intact, but its contents are replaced.

The following example replaces the entire contents of xmlSue with the specified elements. This effectively replaces Sue with Gladys, while keeping Sue's ID number.

    var xmlSue = xmlEmployees..employee.(firstname == "Sue");
    xmlSue.innerXML(<><firstname>Gladys</firstname><lastname>Cravits</lastname><age>43</age></>);

## xml.isProcessingInstruction()

Returns true if xml is an XML processing instruction.

## xmlList.length

Returns the number of items in the list represented by xmlList.

For more on the XMLList data type, see Creating and Using XML Variables.

The following example returns the number of <employee> elements in xmlEmployees. Returns the number 2.

    var numberOfEmployees = xmlEmployees.length;

## xml.namespaces()

Returns an array of Namespace objects that represents any xmlns attribute (with or without a prefix) declared in the entire XML document.

## xml.namespaceURI()

Returns a string representing the namespace URI associated with xml.

The following example returns the namespace URI associated with a SOAP message. Returns a string containing "http://schemas.xmlsoap.org/soap/envelope/”.

    var xmlStockMessage = <Envelope xmlns ="http://schemas.xmlsoap.org/soap/envelope/"
        encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <Body>
            <m:GetLastTradePrice xmlns:m="http://mycompany.com/stocks">
                <symbol>DIS</symbol>
            </m:GetLastTradePrice>
        </Body>
    </Envelope>;
    var ns = xmlStockMessage.Envelope.Body.namespaceURI();

## xml.parent()

Returns the parent of xml.

The following example find the employees whose age is under 30, then uses the parent function to return the entire element containing that person's data. It returns an XML type the element containing John's information.

    var ns = xmlEmployees..employee.(age <= "30").age;
    var emp = ns.parent();

## xml.prependChild(newChild)

Inserts newChild before the existing children of xml.

The following example adds a <prefix> element to the beginning of the element assigned to xmlSue. This code adds <prefix>Mr.</prefix> as the first child of the <employee> node containing information about John.

    var xmlJohn = xmlEmployees..employee.(firstname == "John");

    xmlJohn.prependChild(<prefix>Mr.</prefix>);

## xml.processingInstructions([booleanToLookDeep])

Returns a list of all the XML processing instructions (PIs) from this element's point in the document.

This method can take an optional argument (true or false) signaling to look deep. If no argument is specified, or if false is specified, only PIs which are a sibling to the current element are returned. Otherwise, all PIs from this point down the entire depth of the tree are returned.

## xml.setValue(newValue)

Sets the value (content) of xml to newValue.

## xml.tagName()

Returns the name of the tag for xml.

The following example returns the name of the first child element of the first <employee> element. It returns a string containing "firstname".

    var childTags = xmlEmployees..employee[0].children();

    var firstChildTag = childTags[0].tagName();

## xml.thisXML

Specifies the current XML, such as XML returned from an expression.

For more information, see Specifying the Current XML with the thisXML Property.

## xml.text()

Returns a string containing the value of all XML properties of xml that are of type string.

The following example finds the second child of the second <employee> element and returns its content. It returns a string containing "Sue".

    var ageXML = xmlEmployees..employee[1][1].text();

## xml.toString()

Returns the XML and its contents as a string.

The following example returns a string representation of the first <employee> element.

    var johnText = xmlEmployees..employee[0].toString();

## xml.toXMLString()

Returns an XML encoded string representation of xml.

The following example returns a string representation of the first <employee> element.

    var johnText = xmlEmployees..employee[0].toXMLString();

## xml.xpath(xPathExpression)

Evaluates the XPath expression (specified by xpathExpression) using xml as the context node.

The following example uses an XPath expression to return the <employee> element where the <firstname> element value is "Sue". It returns an XMLList containing the element.

Result: Returns the <employee> element containing information about Sue.

    var xmlSue = xmlEmployees.xpath("//employee[firstname='Sue']")

Related Topics

Handling XML with ECMAScript Extensions

Summary of ECMAScript Language Extensions