给出以下XML:
<Student number=2020 >
<Subject>Comp<Subject>
<Credintials>
<Password>....</Password>
</Credintials>
<PersonalDetails age=30 height=2/>
</Student>
我想得到:
Student
@number
Subject
Credintials
Password
PersonalDetails
@age
@height
按此顺序。
所以基本上如果我解析这个XDocument,我会单独获取元素和单独的属性,这违反了xml层次结构。
var attributes = xDocument.Descendants().Attributes();
var elements = xDocument.Descendants().Elements();
我分别循环这个,因此我首先获得属性然后获取元素
有没有办法使用上面的顺序列出?
答案 0 :(得分:1)
您可以递归返回元素名称,属性名称和子元素:
public IEnumerable<string> GetNodes(XElement xe)
{
yield return xe.Name.ToString();
foreach(XAttribute xa in xe.Attributes())
yield return ("@"+xa.Name);
foreach(XElement xee in xe.Elements())
foreach(var s in GetNodes(xee))
yield return s;
}
用法:
string xml = @"<Student number='2020'>
<Subject>Comp</Subject>
<Credintials>
<Password>....</Password>
</Credintials>
<PersonalDetails age='30' height='2'/>
</Student>";
XDocument x = XDocument.Parse(xml);
var nodes = GetNodes(x.Root);
结果:
IEnumerable<String> (8 items)
------------------------------
Student
@number
Subject
Credintials
Password
PersonalDetails
@age
@height