给定一个Xml文档,您将如何填充属性和元素的路径列表
本文关键字:属性 填充 何填充 元素 路径 列表 一个 Xml 文档 | 更新日期: 2023-09-27 18:29:29
给定以下Xml:
<Student number='2020'>
<Subject>Comp</Subject>
<Credintials>
<Password>010101</Password>
<PasswordLength>6</PasswordLength>
<Contact>contact@example.com</Contact>
</Credintials>
<PersonalDetails age='30' height='2'/>
<Lecture age='30' height='2'>
<StudentName>Hakeem</StudentName>
</Lecture>
</Student>
我想打印出以下列表:
Student.@number=2020
Student.Subject=Comp
Student.Credintials.Password=010101
Student.Credintials.PasswordLength=6
Student.Credintials.Contact=contact@example.com
Student.PersonalDetails.@age=30
Student.Lecture.@age=30
Student.PersonalDetails.@height=2
Student.Lecture.@height=2
Student.Lecture.StudentName=Hakeem
我基本上是在尝试为属性和元素获取这些路径,这些属性和元素的值等于innerText,比如StudentName、Password、Subject。年龄、身高等因素
感谢
这样的方法将打印出您期望的
var xml = @"<Student number='2020'>
<Subject>Comp</Subject>
<Credintials>
<Password>010101</Password>
<PasswordLength>6</PasswordLength>
<Contact>contact@example.com</Contact>
</Credintials>
<PersonalDetails age='30' height='2'/>
<Lecture age='30' height='2'>
<StudentName>Hakeem</StudentName>
</Lecture>
</Student>";
var xmlParsed = XElement.Parse(xml);
GetNodeDescendantsAndPrint(xmlParsed);
public void GetNodeDescendantsAndPrint(XElement node, string nameToAppend= null)
{
var name = string.IsNullOrEmpty(nameToAppend)
? node.Name.LocalName
: nameToAppend;
foreach (var att in node.Attributes())
{
Console.WriteLine(name + ".@" + att.Name.LocalName + "=" + att.Value);
}
var descendants = node.Elements();
if (descendants.Any())
{
foreach (var innerNode in descendants.OfType<XElement>())
{
GetNodeDescendantsAndPrint(innerNode,
name+"." + innerNode.Name.LocalName );
}
}
else
{
Console.WriteLine(name + "=" + node.Value);
}
}