c# - 如何序列化 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);
}
}
解决方案
将 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());
}
}
}
推荐阅读
- javascript - 有什么方法可以在使用 Express Generator 构建的 NodeJS API 上调试 UnhandledPromiseRejectWarning?
- three.js - 三.js fbxloader 示例 99% 成功
- javascript - 如何在 nodejs/javascript 中解析 Azure Blob URI?
- php - PHP删除匹配字符后替换3个字符
- android - 如何在 Oreo 中控制 WindowManager 覆盖优先级?
- firebase - Cloud Functions for Firebase 中的套接字挂起错误
- javascript - 如何使用本机 javascript 从窗口中删除特定事件侦听器
- jsf - 尝试从 icefaces 迁移到 primefaces 时出错
- javascript - 如何在单独的 javascript 文件中引用传递给局部视图的参数?
- python - 搜索和替换引用列表