Chaos Spindash
Chaos Spindash

Reputation: 35

C# Select XML node by another node

I'm new to XML in programming, so I need help with this one:

I have a XML file like this:

<?xml version="1.0" standalone="yes"?>
<contestants>
  <fighter>
    <Name>Ryu</Name>
    <Folder>ryu</Folder>
  </fighter>
  <fighter>
    <Name>Ken</Name>
    <Folder>ken</Folder>
  </fighter>
  <fighter>
    <Name>M. Bison</Name>
    <Folder>m_bison</Folder>
  </fighter>
  [...]
</contestants>

Now I want to select the folder node based on the name node, something like this in SQL:

SELECT Folder FROM contestants WHERE Name='Ryu'

What is the best way to do so? I've already been looking for some answers, but the only provide the solutions for attributes, not for nodes.

Upvotes: 1

Views: 111

Answers (1)

santosh singh
santosh singh

Reputation: 28672

Try following code snippet

  void Main()
{
    XElement root = XElement.Load(@"c:\temp\a.xml");
    var result = root.Elements("fighter")
               .Where(i => (string)i.Element("Name") == "Ryu")
               .Select(i => (string)i.Element("Folder"));
    foreach (var element in result)
    {
        Console.WriteLine(element);
    }
}

Upvotes: 1

Related Questions