首页 > 解决方案 > 如何序列化 xml 并获得最深的节点

问题描述

我有以下 xml 文件

<?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>

我想序列化该xml,但我希望page1节点中的所有子节点都可以像属性一样处理,例如:

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%

换句话说,我只对将它们序列化为对象的最深节点感兴趣。

我有一个序列化方法,但我不知道如何构建类。

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

            using (var reader = doc.Root.CreateReader())
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
        }

标签: c#xmlserializationdeserializationlinq-to-xml

解决方案


将 xml linq 与字典一起使用:

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());
        }
    }
}

推荐阅读