Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DOM and whitespace

 
Brian Nice
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm using xerces to parse an XML document. Do you always have to check the node type to ensure that you are actually getting an element when you are traversing through the document? For example, if I have the xml
<root>
<numbers>
</one>
</two>
</numbers>
</root>
and i am at the <root> and I do get ChildNodes, I get a nodelist consisting of numbers. If I immediately get the childnodes of that, then i always get #text returned instead of <one> or <two>. So i have to loop through the child nodes until i find an NODE.ELEMENT_NODE to be sure I have <one> or <two>.
Is there anyway to ignore the whitespace so you can just use the api calls directly without having to loop through the nodelist all the time to get what you want?
Hope that makes sense. Thanks
Brian
 
Dhinakar
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian,
Did you try setIgnoringElementContentWhitespace(true) in the DocumentBuilderFactory.
DocumentBuilderFactory.setIgnoringElementContentWhitespace(true)

------------------
Dhina
 
Brian Nice
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that still leaves me with a bunch of #text nodes. I am just using the below method:

Is there a way to just get the elementNodes? Otherwise I am always looping through the nodelist to find an node type of element_node which seems pretty wasteful...
Thanks
Brian
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian,
To use Dhina's trick, you need to have a DTD, otherwise your parser cannot determine that your element has an "element only content model".
Another alternative (only if you use a DOM Level 2 Core compliant DOM implementation) would be to use a Node iterator or a Tree walker with the help of the DocumentTraversal interface which is implemented through the Document object. Below is an example using the Node iterator:

Cheers,
Beno�t
[This message has been edited by Beno�t d'Oncieu (edited August 29, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic