0

XML

<?xml version="1.0" encoding="utf-8" ?> 
<animals>
    <animal id="fisrt">
        <type>Dog</type>
        <name>Han</name>
    </animal>
    <animal id="second">
        <type>Cat</type>
        <name>Leia</name> 
    </animal>
</animals>

C#

using System.Xml.Linq;

string id = "second";
var filter = from ab in element.Elements("animal") where ab.Attribute("id").Equals(id) select ab;
foreach (XElement selector in filter)
{
    label1.Content = selector.Element("name").Value;
}

What I need help with is selecting elements based on the parent element's id. The goal is to select the name who's parent's id is "second", so I'm trying to get "Leia". The problem I'm encountering is that nothing is happening to the label.

What am I doing wrong and how can I fix this issue. I'm also open to different approach if someone knows of a better way of achieving my goal.

4

2 回答 2

1

您错过了检查属性的值:

where ab.Attribute("id").Value.Equals(id)

希望这有帮助!

于 2013-05-18T02:49:49.943 回答
-1

这个怎么样:

string name = xdoc.Elements("animal")
     .Where (e=>e.Attribute("id")=="first")
     .Elements("name")
     .Select(e=>e.Value)
     .FirstOrDefault();

本质上,您希望将关于id属性的条件放在 中where并继续查询。

我知道这是方法注释而不是 linq 语法,我更喜欢它,因为当事情变得多毛时更容易阅读。

于 2013-05-18T02:49:20.243 回答