在反序列化每个父级和子级中都有唯一标识符的XML文件时,是否可以维护父子关系。例如,如果“Name”标记始终包含唯一ID,那么在以下XML中维护父子关系的最佳方法是:
<Building>
<Name>Bldg 1</Name>
<Room>
<Name>Room 1</Name>
<Table>
<Name>Table 1</Name>
</Table>
</Room>
</Building>
在类中有一个属性,用于容纳“Name”标记中父节点的文本值,以及父名称的标记。例如,名为“Room 1”的“Room”标签将具有父节点名称的属性,即“Bldg 1”和父节点标签的属性,即“Building”。我无法控制架构,但这是数据格式的简化版本。
答案 0 :(得分:0)
我不反对序列化。只是使用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
{
static void Main(string[] args)
{
string input =
"<Root>" +
"<Building>" +
"<Name>Bldg 1</Name>" +
"<Room>" +
"<Name>Room 1</Name>" +
"<Table>" +
"<Name>Table 1</Name>" +
"</Table>" +
"</Room>" +
"<Room>" +
"<Name>Room 2</Name>" +
"<Table>" +
"<Name>Table 1</Name>" +
"</Table>" +
"</Room>" +
"</Building>" +
"<Building>" +
"<Name>Bldg 2</Name>" +
"<Room>" +
"<Name>Room 1</Name>" +
"<Table>" +
"<Name>Table 1</Name>" +
"</Table>" +
"</Room>" +
"<Room>" +
"<Name>Room 2</Name>" +
"<Table>" +
"<Name>Table 1</Name>" +
"</Table>" +
"</Room>" +
"</Building>" +
"</Root>";
XElement root = XElement.Parse(input);
var results = root.Descendants("Building").Select(x => new
{
name = x.Element("Name").Value,
rooms = x.Elements("Room").Select(y => new
{
name = y.Element("Name").Value,
Tables = y.Elements("Table").FirstOrDefault().Element("Name").Value
}).ToList()
}).ToList();
}
}
}