I have xml as below. How can I get the Id such as 2222 if name = mobile. I have like to retrieve Id value base on name value.
Xml Example
<Type>
<id>1111</id>
<name>Laptop</name>
<Type>
<Type>
<id>22222</id>
<name>Mobile</name>
<Type>
I have tried below code but not working.
XElement xel = root
.Elements("Type").Element("id")
.Where(x => (int)x.Element("name") == "Mobile")
.SingleOrDefault();
Try something like this:
string xml = @"
<Types>
<Type>
<id>1111</id>
<name>Laptop</name>
</Type>
<Type>
<id>22222</id>
<name>Mobile</name>
</Type>
</Types>
";
XElement root = XElement.Parse(xml);
string name = "Mobile";
string id = root
.Elements("Type")
.Where(x => (string)x.Element("name") == name)
.Select(x => (string)x.Element("id"))
.SingleOrDefault();
Console.WriteLine(id); // Outputs "22222"
What about this:?
string xml = @"
<Type>
<id>1111</id>
<name>Laptop</name>
</Type>
<Type>
<id>22222</id>
<name>Mobile</name>
</Type>
";
XElement root = XElement.Parse(xml);
XElement type = root
.Descendants("Type")
.FirstOrDefault(x => x.Element("name").Value == "Mobile");
if (type != null)
{
XElement id = type.Element("id");
if (id != null)
{
Console.WriteLine("Id: " + id.Value);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.