Home » c# » c# – How to Serialize xml and get just deepest nodes

c# – How to Serialize xml and get just deepest nodes

Posted by: admin February 21, 2020 Leave a comment


I have the following xml file

<?xml version="1.0" encoding="utf-8"?>
        <file_name Value="" />
        <date Value="" />
                <percentage Value="90%" />                
                <profit Value="50%" />                
                <total Value="$1500" />                

and I want to serialize that xml but I want that all subnodes in page1 node could be handle like properties, for example:

var xmlInfo = new List<xmlClass>();
var FieldName = xmlInfo[0].FieldName; // the value of FieldName should be percentage
var data = xmlInfo[0].Value; // the value of data should be 90%

In other words, I’m only interested in the deepest nodes to serialize them into an object.

I have a serialization method, but I don’t know how to build the class.

public static T Deserialize<T>(XDocument doc)
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var reader = doc.Root.CreateReader())
                return (T)xmlSerializer.Deserialize(reader);
How to&Answers:

Use xml linq with a dictionary :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
    class Program
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Descendants("page1")
                .GroupBy(x => x.Name.LocalName, y => (string)y.Attribute("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());


The XPath expression //*[not(child::node())] returns all elements without child nodes (either child elements or child text nodes), if that matches your definition of “deepest”.