映射XML文件的节点

时间:2015-02-21 11:48:34

标签: c# xml recursion

我有一个深度为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

1 个答案:

答案 0 :(得分:0)

您可以使用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;
}
相关问题