DOMExample first creates a DOM document by parsing an XML document. The file it parses is one that you specify on the command line.
static Document document; ... DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse( new File(args[0]) ); ...
Next, the example creates a SOAP message in the usual way. Then it adds the document to the message body:
SOAPBodyElement docElement = body.addDocument(document);
This example does not change the content of the message. Instead, it displays the message content and then uses a recursive method, getContents, to traverse the element tree using SAAJ APIs and display the message contents in a readable form.
public void getContents(Iterator iterator, String indent) { while (iterator.hasNext()) { Node node = (Node) iterator.next(); SOAPElement element = null; Text text = null; if (node instanceof SOAPElement) { element = (SOAPElement)node; QName name = element.getElementQName(); System.out.println(indent + "Name is " + name.toString()); Iterator attrs = element.getAllAttributesAsQNames(); while (attrs.hasNext()){ QName attrName = (QName)attrs.next(); System.out.println(indent + " Attribute name is " + attrName.toString()); System.out.println(indent + " Attribute value is " + element.getAttributeValue(attrName)); } Iterator iter2 = element.getChildElements(); getContents(iter2, indent + " "); } else { text = (Text) node; String content = text.getValue(); System.out.println(indent + "Content is: " + content); } } }