Accessing XML node single/multiple values

D

Dahak

It seems that my GoogleFu has failed me tonight and I'm hoping I
can find some advice.


I've inherited a ASP.NET project written in Visual Basic.

I'm not too familiar with the .NET framework or XML, so bear with
me.

The project is about 95% complete, but the XML parser needs quite
a bit of tightening.

One early problem I had was having the script crash when
attempting to access an XmlTextReader node that didn't exist. I've
since learned to check to see if the node IS NOTHING to prevent an
actual read attempt on the non-existent node.

My current troubles happen when trying to deal with a node that
may - or may not - have multiple elements. For instance, there may be
one or more //ShipTo/Address/PostalAddress/DeliverTo elements.

I know that when there is _one_ element, I can access the node
with doc.SelectSingleNode(//Node/Path).InnerText.

I know that when there is _more than one_ element, I can access
the node with doc.SelectSingleNode(//Node/Path).Item(x).InnerText.

But how do I properly test for the element node having a single or
multiple values?

I don't recall having any success with
doc.SelectSingleNode(//Node/Path).Item(0).InnerText when the node
wasn't actually a list.

Any thoughts would be appreciated.


Thanks.

-Joe
 
O

\(O\)enone

Dahak said:
My current troubles happen when trying to deal with a node that
may - or may not - have multiple elements. For instance, there may be
one or more //ShipTo/Address/PostalAddress/DeliverTo elements.

Have you tried using doc.SelectNodes instead of doc.SelectSingleNode?

This uses the same XPath syntax as SelectSingleNode, but returns an
XmlNodeList, which is basically a collection of all the matching nodes. You
can then query the Count property to find how many nodes there were (zero,
one or more are all possible return values here) and access the individual
nodes using the default Item property.

HTH,
 
D

Dahak

Have you tried using doc.SelectNodes instead of doc.SelectSingleNode?

This uses the same XPath syntax as SelectSingleNode, but returns an
XmlNodeList, which is basically a collection of all the matching nodes. You
can then query the Count property to find how many nodes there were (zero,
one or more are all possible return values here) and access the individual
nodes using the default Item property.

HTH,

I'll give that a whirl. I wasn't aware of how else the node data
could be accessed.


Like I said, VB.NET/XML isn't my thing, but the instances where I
need to determine how to access the node values (0/1/many) have been
causing the program to crash on me when an accessed node has more/less
items than I am looking for.

Thanks for the tip.

-JPB
 

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

Similar Threads


Top