提问人:VInayK 提问时间:9/28/2023 更新时间:9/28/2023 访问量:55
C# 如何反序列化嵌套相同节点的 XML 字符串 [duplicate]
C# how to deserialize XML string which has nested same node [duplicate]
问:
<n-hierarchy>
<n name="ABC" n_id="971" />
<n name="XYZ" n_id="972">
<n name="jkl" n_id="973">
<n name="wer" n_id="974"/>
<n name="cvb" n_id="975"/>
</n>
</n>
</n-hierarchy>
上面是我从 API 收到的示例 XML 字符串,我想反序列化为 C# 对象
答:
0赞
jdweng
9/28/2023
#1
请尝试以下操作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApp10
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement hier = doc.Descendants("n-hierarchy").FirstOrDefault();
Node root = new Node();
root.name = "root";
root.parse(hier);
}
}
public class Node
{
public string name { get; set; }
public string id { get; set; }
public List<Node> children { get;set;}
public void parse(XElement element)
{
foreach (XElement childElement in element.Elements("n"))
{
if (children == null) children = new List<Node>();
Node child = new Node();
children.Add(child);
child.name = (string)childElement.Attribute("name");
child.id = (string)childElement.Attribute("n_id");
child.parse(childElement);
}
}
}
}
上一个:内联 XML 元素
评论