2

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 ?

1

3 Answers 3

3

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:

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.