0

I have the following xml file

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

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);
            }
        }
Edgwin
  • 61
  • 1
  • 1
  • 7

2 Answers2

0

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")
                .First()
                .Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y.Attribute("Value"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

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".

Michael Kay
  • 156,231
  • 11
  • 92
  • 164