【问题标题】:How to Serialize xml and get just deepest nodes如何序列化 xml 并获得最深的节点
【发布时间】:2020-02-20 00:40:33
【问题描述】:

我有以下 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);
            }
        }

【问题讨论】:

  • 是什么让 XML “特别”? xmlClass 是什么?
  • 我只是改标题
  • 您能否更具体地了解“最深节点”?您不希望它从“file_name”和“date”中获取值吗?

标签: c# xml serialization deserialization linq-to-xml


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    XPath 表达式//*[not(child::node())] 返回所有没有子节点的元素(子元素或子文本节点),如果这与您对“最深”的定义相匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2015-05-22
      • 2022-06-27
      相关资源
      最近更新 更多