tags:

views:

51

answers:

1

iterate and get the values of ProductName and ProductId for each node. what is the xpath syntax. Please help

Here is the xml file:

<Products>
    <Product>
        <ProductName>PDPArch</ProductName>
        <ProductId>57947</ProductId>
    </Product>
    <Product>
        <ProductName>TYFTType</ProductName>
        <ProductId>94384</ProductId>
    </Product>
</Products>
A: 

OK, had to rearrange things a bit. YOu'll need to do something like this:

while (nodes.MoveNext())
{
   // here, we're on the Product node
   string productName = null;
   string productId = null;

   // does it have child nodes?    
   if (nodes.Current.HasChildren)
   {
      // go to the first child node
      bool hasMore = nodes.Current.MoveToFirstChild();

      while (hasMore)
      {
         // extract the info
         if (nodes.Current.Name == "ProductName")
         {
             productName = nodes.Current.Value;
         }

         if (nodes.Current.Name == "ProductId")
         {
            productId = nodes.Current.Value;
         }

         // does it have more children?
         hasMore = nodes.Current.MoveToNext();
      }
   }
}

Marc

UPDATE:
An easier way to do this might be this:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Your XML file name.xml");

XmlNodeList list = xmlDoc.SelectNodes("/Products/Product");

foreach(XmlNode node in list)
{
  string productName = node.SelectSingleNode("ProductName").InnerText;
  int productID = Convert.ToInt32(node.SelectSingleNode("ProductId").InnerText);
}

No messy XPathIterator and navigator and everything...... this works in .NET 1.x and 2.x and up.

In .NET 3.5 and up, you could also use Linq-to-XML to parse the XML more easily.

marc_s
Let me test it out
sa
What its doing is getting the ProductName from the next node instead of ProductId from the current node?
sa
@marc_s: This leaves me puzzled - why did you implement a complicated iteration when `SelectNodes()` and some trivial XPath would have been enough?
Tomalak
@Tomalak: because the OP had this (sort of) in his original question, and I didn't want to totally change everything.
marc_s
In the meantime, I've found the original question. :-)
Tomalak
okay. I am a newbie and hence the complicated way. Is there a optimized way of achieving this result
sa
Thanks for the wonderful solution!!
sa