XML traversal in levelorder

C

C. Rühl

Hi,

I would like to traverse a XML document in levelorder. My next steps
depend on different nodes and their levels.

What I did by now was to set up a XmlStreamEventReader to easily
choose the next steps for each node and node-type:

m_in = new FileInputStream(file);
m_factory = XMLInputFactory.newInstance();
m_parser =
m_factory.createXMLEventReader(m_in);

// parse events
while(this.m_parser.hasNext())
{
XMLEvent event = m_parser.nextEvent();

switch(event.getEventType())
{
case
XMLStreamConstants.START_DOCUMENT:
break;

case XMLStreamConstants.START_ELEMENT:
StartElement startElement = event.asStartElement();

// common mib files
if(startElement.getName().toString()=="Common")
newCommonInstance(startElement);

....

The XmlStreamEventReader traverses the XML file in preorder.

And because of my XML file only consists of nodes with attributes (so
there's no node-value only attributes an their values), working with a
DOM is pretty strange. As soon as I walk through the nodes my root has
i.e. 5 instead of actually 2 children:

root
#text
node1
#text
node2
#text

How do I get rid of the "#text"-blanks or what should I do to
correctly traverse in levelorder?
 
C

C. Rühl

Okay, I just started over from scratch. I'm parsing the file now into
a DOM and give the XML root node to a method like shown here:

private void visitNodes(Node node)
{
try
{
// child nodes of current node
NodeList nodeList = node.getChildNodes();

// loop through child nodes
for(int i=0; i<nodeList.getLength(); i++)
{
if(nodeList.item(i).getLocalName()=="Component")
{
System.out.println(nodeList.item(i).getLocalName());
}
}
}
catch(Exception ex)
{
// nothing yet
}
}

But XML level-order traversal ain't that easy... How and where can I
now insert a recursive call of that method? I can't just put it into
the for-loop, because then I get pre-ordered results. So what should I
do to traverse my file in level-order (breadth-first)?

I hope that someone gives me a little help here. Thanks a lot!

The XML file looks a little like this:

<Component>
<Component>
<Component/>
<Component/>
</Component>
<Component/>
</Component>
 
C

C. Rühl

Solution found:

Queue q = new Queue();
q.enqueue(node);

while(!q.isEmpty())
{
node = (Node) q.dequeue();

if(node.getLocalName()=="TopLevelComponent"
|| node.getLocalName()=="Component"
|| node.getLocalName()=="SubComponent")
{
System.out.println(node.getAttributes().item(2).getNodeValue() +
m_mncn);
m_mncn++;
}

NodeList children = node.getChildNodes();

for(int i=0; i<children.getLength(); i++)
q.enqueue(children.item(i));
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,006
Messages
2,570,265
Members
46,860
Latest member
JeremiahCo

Latest Threads

Top