skip to Main Content

I am trying to select a xml value by matching on the value of the id tag before it

<unit>
  <id>1</id>
  <name>foo</name>
</unit>
<unit>
  <id>2</id>
  <name>bar</name>
</unit>

Given my id is 2 in the above scenario I would like to get the value ‘bar’.

Any advice or library suggestions to do this is appreciated.

2

Answers


  1. I would use LINQ to XML for this:

    • Find the element you want
    • Use its Parent property to get to the unit
    • Use the Element method to get the name

    Sample code:

    using System.Xml.Linq;
    
    XDocument doc = XDocument.Load("test.xml");
    var id = doc.Descendants("id").Where(id => id.Value == "2").SingleOrDefault();
    if (id is null)
    {
        Console.WriteLine("No such ID");
        return;
    }
    else
    {
        var unit = id.Parent;
        var nameElement = unit?.Element("name");
        if (nameElement is null)
        {
            Console.WriteLine("No name element");
            return;
        }
        string name = nameElement.Value;
    
        Console.WriteLine($"Name: {name}");
    }
    
    Login or Signup to reply.
  2. You can do this in a simple one liner using Linq-to-XML, after loading your file into XDocument.

    XDocument doc = XDocument.Load("test.xml");
    // alternatively XDocument.Parse
    
    var name = doc.Elements("unit")
        .FirstOrDefault(unit => unit.Element("id")?.Value == "2")
        .Element("name")?.Value;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search