2015-02-21 3 views
0

У меня есть файл XML с глубиной-N. (N может отличаться) Я хочу перемещать все узлы и разбирать имена узлов в список строк. В основном я хочу, чтобы преобразовать следующийmap узел XML-файла

<?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 
+0

Я написал неудачную рекурсию и проверил http://stackoverflow.com/questions/847978/c-sharp-how-can-i-get-all-elements -name-from-a-xml-file, который близок к моему, но все еще пытается понять, как его адаптировать. – user4591106

ответ

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; 
} 
Смежные вопросы