Вопрос

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.

Это было полезно?

Решение

You miss to check the value of attribute:

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

Hope this help!

Другие советы

How about this:

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

Essentially you want to put the condition about id attribute inside the where and continue the query.

I know this is the method annotation instead of linq syntax, I prefer it for being easier to read when things get hairy.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top