How Do I: Work with XML Documents Directly?

XML maps allow you to control how XML messages are mapped to the Java arguments and return value of a method. However, sometimes you want to get at the XML directly, without using a map of any kind.

To Receive the Input of a Method as Raw XML

1. In Source View, at the top of your web service, add an import for the XML Document Object Model (DOM) classes:

    import org.w3c.dom.*;

2. Edit the method that will be receiving XML so that the parameter holding the XML is a org.w3c.dom.Node object.

This gives you direct access to the XML sent to your web service. You can access the data using the DOM programming API. For more information about the API, see Xerces API Documentation.

To Generate Raw XML for the Return value of a Method

1. In Source View, at the top of your web service, add imports for the DOM classes and for the Xerces Document implementation.

    import org.w3c.dom.*;
    import org.apache.xerces.dom.DocumentImpl;

2. In your method, you first must create a Document object. This object will be used as a factory for creating nodes in the XML tree.

    Document doc = new DocumentImpl();

3. Create the root tag of the XML to return by calling createElement.

    Element root = doc.createElement("myTag");

4. You can set the attributes on the tag by calling setAttribute.

    root.setAttribute("myAttr", "value");

5. You can add child tags by calling appendChild.

    Element child = // ...
    root.appendChild(child);

6. You can add text into the body of the tag by appending a child node that is a Text object.

    child.appendChild(doc.createTextNode("some text"));

7. At the end of your method, return the root tag of the XML.

    return root;

Related Topics

Handling XML with ECMAScript Extensions

Handling and Shaping XML Messages with XML Maps