Question

I have a while loop that reads in a flat file one line at a time and parses out information and then adds it to an XML file. Some of the information has to be transformed by calling a web service and I am having trouble pulling out the required values from the response XML.

Here is the XML I need to grab values out of:

<?xml version="1.0"?>
<Root>
    <Tags>
        <WTs>
            <WT>
                <ID>ID_1</ID>
                <Value>Value 1</Value>
            </WT>
            <WT>
                <ID>ID_2</ID>
                <Value>Value 2</Value>
            </WT>
            <WT>
                <ID>ID_3</ID>
                <Value>Value 3</Value>
            </WT>
        </WTs>
    </Tags>
</Root>

I tried using both Linq and xpath to grab the values. What I need is to check the ID of each WT element and if it is the one I want, then grab the Value element.

Here is the C# code:

var xdoc = XDocument.Parse(retValue);
string val1 = xdoc.Root.Elements("WTs")
      .Where(q => (string)q.Element("ID") == "ID_1")
      .Select(q => (string)q.Element("Value"))
      .FirstOrDefault();
Console.WriteLine("\n\n\nVal 1 = {0}\n\n\n", val1);

val1 = (string)xdoc.XPathSelectElement("//WTs/WT[ID='ID_1']/Value");
Console.WriteLine("\n\n\nVal1 = {0}\n\n\n", val1);

When I debug, the val1 variable is set to null. I think the problem might be with the Tags node being a child of the Root element and a parent to all the other nodes. I tried using something like xdoc.Root.FirstNode but this only allows me to choose elementsafterself and elementsbeforeself. I don't know how to access the children elements.

How can I grab the Value node based on the ID node's value?

Was it helpful?

Solution

You are missing Tags and WT elements in your query:

string val1 = xdoc.Root.Element("Tags").Element("WTs").Elements("WT")
                  .Where(q => (string)q.Element("ID") == "ID_1")
                  .Select(q => (string)q.Element("Value"))
                  .FirstOrDefault();

Or simply look for descendatns

string val1 = xdoc.Root.Descendants("WT")
                  .Where(wt => (string)wt.Element("ID") == "ID_1")
                  .Select(wt => (string)wt.Element("Value"))
                  .FirstOrDefault();

XPath solution will look like

string val1 = (string)xdoc.XPathSelectElement("//WT[ID='ID_1']/Value");

OTHER TIPS

XPath would be my approach:

/Root/Tags/WTs/WT[ID = TargetValue]/Value

should do it, I realise that is very similar to what you show. I would start by double checking xdoc is what you think it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top