tags:

views:

131

answers:

3
+2  Q: 

Java Dom question

Actually I have an XML document. I would like to print the children of the root element of the document using a utility in org.w3c.Dom without printing the document headers.

So I need a utility in org.w3c.Dom to print a Node only. any help please ?

A: 

Printing isn't the job of the Java DOM API. There are no printing APIs in it at all.

You can certainly visit the children of the root element, look at the type of each Node, and print what you want to print.

bmargulies
+3  A: 

Assuming you have an org.w3c.dom.Document you can print the names of the child nodes of the root element with something like:

// assuming: Document doc = ...;

NodeList childNodes = doc.getDocumentElement().getChildNodes();
for(int i = 0; i < childNodes.getLength(); i++){
    System.out.println(childNodes.item(i).getNodeName());
}

Realistically, if you want to navigate the DOM using the org.w3c.dom utilities you'll need to figure out which API calls are most relevant for you.

An excellent starting point is the API documentation (that I referred to to answer your question). Here's the relevant pages for this particular answer:

Mark E
getChildNodes() returns a NodeList, not a collection or array. As such it cannot be used in a for loop as you suggest.
Jherico
@Jherico, that's unfortunate, guess I just assumed it implemented one of the Collection interfaces, fixed accordingly.
Mark E
A: 

I have an XML utility class that I use for simple DOM functionality. In this case you would be able to use the XmlUtil.writeXml(Node node, Writer writer) to write individual subtrees of a document.

The source code is available here

Jherico
Thank you :) for your care
James