[英]How to get data using xelement C#
I have xml as below.我有如下的 xml。 How can I get the Id such as 2222 if name = mobile.如果名称 = 手机,我如何获得 2222 之类的 ID。 I have like to retrieve Id value base on name value.我想根据名称值检索 Id 值。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.