0

I have the following XML structure:

<?xml version="1.0" encoding="utf-8"?>
<xml>
  <root>
    <Item>
      <taxids>
        <string>330</string>
        <string>374</string>
        <string>723</string>
        <string>1087</string>
        <string>1118</string>
        <string>1121</string>
      </taxids>
    </Item>
  </root>
</xml>

I need to get all the string nodes from the xml file to a string variable, like this:

var query = from ip in doc.XPathSelectElements("xml/root/Item")
            where ip.XPathSelectElement("taxid").Value == "723"
            select ip.XPathSelectElements("taxids").ToString();

But I am getting the following in one row of the variable query:

"System.Xml.XPath.XPathEvaluator+<EvaluateIterator>d__0`1[System.Xml.Linq.XElement]"

I want to get a string like this:

  <taxids><string>330</string><string>374</string><string>723</string><string>1087</string><string>1118</string><string>1121</string></taxids>

Is this possible?

Thanks!

2 Answers 2

1

I would suggest you something like:

var values = from ids in doc.XPathSelectElements("/xml/root/Item/taxids")
                     from id in ids.XPathSelectElements("string")
                     where id.Value.Contains("723")
                     select ids.ToString();

var result = string.Join("", values);

The value variable will contain all the taxids, which have at least one string child with value 723.

Another variant, which doesn't use XPath for the children checking:

var values = from ids in doc.XPathSelectElements("/xml/root/Item/taxids")
                     from id in ids.Elements("string")
                     where id.Value.Contains("723")
                     select ids.ToString();

var result = string.Join("\n", values);
Sign up to request clarification or add additional context in comments.

2 Comments

It is not the purpose to get the first. i only gave an example. but this wont work. You are doing the same as me. or am i wrong?
I have updated my answer. This will now work. I've checked it.
0
var doc = XDocument.Parse(@"<?xml version=""1.0"" encoding=""utf-8""?>
<xml>
<root>
<Item>
<taxids>
<string>330</string>
<string>374</string>
<string>723</string>
<string>1087</string>
<string>1118</string>
<string>1121</string>
</taxids>
</Item>
</root>
</xml>");

var query = doc.XPathSelectElement("xml/root/Item/taxids");

Console.WriteLine(query);

2 Comments

Hi. but i need to do a linq query so i can filter the results.. should this work also?
@Ozkan, What do you mean? It works as you wrote in your question? Please update your question with detailed information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.