1

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.

1
  • 1
    I suggest you read a LINQ to XML tutorial - and note that if you cast an XElement to string, it will return the text value within the element. Commented Dec 31, 2017 at 13:20

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.