Search code examples
c#xmlxelement

How to filter elements from XML file


I can read a xml file to the console. But I need only some elements from the xml file. Like Sender Name, Postalcode, weight and value. Because now all the element from the xml file are returned.


Solution

  • You can try XDcoument with LINQ

    XDocument xdoc = XDocument.Load($"XMLFile1.xml");
    
    var items = xdoc.Descendants("Parcel")
                    .Select(xelem => new
                    {
                        Name = xelem.Element("Sender").Element("Name").Value,
                        PostalCode = xelem.Element("Sender").Element("Address").Element("PostalCode").Value,
                        Weight = xelem.Element("Weight").Value,
                        Value = xelem.Element("Value").Value
                    });
    
    foreach (var item in items)
    {
        Console.WriteLine($"{ item.Name} - { item.PostalCode} - { item.Weight} - { item.Value}");
    }