tags:

views:

82

answers:

2

Scenario:

I am parsing values from an XML file using C# and have the following method:

    private static string GetXMLNodeValue(XmlNode basenode, string strNodePath)
    {
        if (basenode.SelectSingleNode(strNodePath) != null)
            return (basenode.SelectSingleNode(strNodePath).InnerText);
        else
            return String.Empty;
    }

To get a particular value from the XML file, I generally pass the root node and a path like "parentnode/item"

I recently ran into an issue where two nodes at the same document level share the same name.

Why:

The duplicate nodes all need to be read and utilized; they have child nodes with differing values (which can distinguish them). At present I just have two nodes, each named <Process> and sub-nodes named <Name> which contain unique names. Other sub-nodes contain various values such as memory usage. When processing and storing the values for the sub-nodes, I would essentially ignore the parent node name and use my own names based on the sub-node <Name> value.

Question:

What is the best way to get the values for duplicate-named nodes distinctly? My thought was to load all values matching the node name into an array and then using the array index to refer to them. I'm not sure how to implement that, though. (I'm not well-versed in XML navigation.)

Sample XML

<?xml version="1.0" ?>
<info>
  <processes>
    <process>
        <name>program1</name>
        <memory_use>24.8</memory_use>
    </process>
    <process>
        <name>program2</name>
        <memory_use>19.0</memory_use>
    </process>
  </processes>
</info>
+1  A: 

The answer to your question is, "it depends".

It depends on what you intend to do with the "duplicate" nodes. What does it mean for there to be more than one with the same name? Was it an error in the program that generated the XML? Was it correct, and an unlimited number of such nodes is permitted? What do they mean when there are more than one?

You need to answer those questions first, before designing code that processes "duplicate" nodes.

John Saunders
I'll elaborate on this more in the question, thanks for bringing the point up.
JYelton
+3  A: 

Use SelectNodes method instead it gives you a list of all nodes matching your Xpath

mfeingold
I'll go look this up, it sounds like this would return an array where I could iterate each result?
JYelton
It returns an `IEnumerable` of nodes. You can use `foreach` to loop over them.
John Saunders
This worked; thank you, mfeingold and John.
JYelton