映射XML文件的节点

用户4591106

我有一个深度为N的XML文件。(N可能会有所不同)我想遍历所有节点并将节点名称解析为字符串列表。基本上我想改变以下

<?xml version="1.0" encoding="utf-8" ?>
<person>
    <name></name>
    <surname></surname>
    <dateofbirth></dateofbirth>
    <phones>
        <phone>
            <countrycode></countrycode>
            <areacode></areacode>
            <number></number>
            <extension></extension>
        </phone>
        <phone>
            <countrycode></countrycode>
            <areacode></areacode>
            <number></number>
            <extension></extension>
        </phone>
    </phones>
</person>

进入

person
person.name
person.surname
person.dateofbirth
person.phone.countrycode
person.phone.areacode
person.phone.number
person.phone.extension
用户名

您可以使用XDocument使用以下代码获取结果:

public List<string> GetList()
{
    List<string> result = new List<string>();
    XDocument d = XDocument.Load(@"c:\text.xml");
    foreach (var name in d.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct())
    {
        XElement xe = (from c in d.Descendants(name.ToString()) select c).FirstOrDefault();
        string fullName = getFullName(xe, d, "");
        string[] sarr = fullName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
        Array.Reverse(sarr);
        string result = string.Join(".", sarr);
        result.Add(result);
    }
}
private string getFullName(XElement elem, XDocument doc, string prevName)
{
    if (elem.Parent == null)
    {
        prevName += "." + elem.Name.ToString();
    }
    else
    {
        prevName += "." + getFullName(elem.Parent, doc, elem.Name.ToString());
    }

    return prevName;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章