开发者

Java Dom question

Actually I have an XML document. I would like to print the children of the root elem开发者_开发问答ent 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 ?


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:

  • Package Summary
  • Document
  • getDocumentElement
  • Element
  • getChildNodes
  • NodeList
  • Node


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜