Xmlelement condition to get value of another element using c#

i have an xmldoc with multiple records. eg:

<value> <id>aaaaa</id> <condition>true</condition> </value>  <value> <id>bbbb</id> <condition>false</condition> </value>  <value> <id>ccccc</id> <condition>true</condition> </value> 

now using c# and xml linq
i need to check the condition element value’s if it is true then i need to pass its id value to string

code i used :

XmlDocument doc = new XmlDocument(); doc.Load(@"D:\Downloads\file.xml");  XmlElement xml= doc.DocumentElement; XmlNodeList cond= xml.SelectNodes("/value/condition"); XmlNodeList id= xml.SelectNodes("/value/id");  foreach (XmlElement node in cond) {     var value = node.InnerText;      if (value == "true")     {         var id_values = id.InnerText;         Console.WriteLine(id_values);         Console.ReadKey();     } } 

in this code im not able to get id value of condition which is true. it returns all id’s but i need only id value which is against true condition.

Add Comment
2 Answer(s)

You need to select the "value" nodes and analyze then in your loop. For example to get you started:

var s = @"<?xml version=""1.0"" encoding=""utf - 8""?> <values> <value> <id>aaaaa</id> <condition>true</condition> </value>  <value> <id>bbbb</id> <condition>false</condition> </value>  <value> <id>ccccc</id> <condition>true</condition> </value> </values>";  XmlDocument doc = new XmlDocument(); doc.LoadXml(s);  var nodes = doc.SelectNodes("/values/value"); foreach (XmlElement node in nodes) {     if (node.SelectSingleNode("condition").InnerText == "true")     {         Console.WriteLine(node.SelectSingleNode("id").InnerText); // prints "aaaaa" and "ccccc"     } } 
Answered on July 16, 2020.
Add Comment

Please look into the basics of linq to xml. It has number of apis for easy navigaton.

XElement.Load("file")    .Elements(XName.Get("value"))    .Where(x => x.Element("condition").Value.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))    .Select(x => x.Element("id").Value); 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.