2016-11-07 15 views
0

比方說,我有一個Person類:使用的XElement解析這個XML到數組

public class Person 
{ 
    public string Name { get; set; } 
} 

如何解析包含

<person> 
    <name>a</name> 
</person> 
<person> 
    <name>b</name> 
</person> 

成兩個Person秒的數組的XML文件?

這是這個問題的一個變種:Specific parsing XML into an array

唯一的區別是,有沒有<people></people>圍繞整個XML。 <person>即刻開始。

+6

如果沒有外根標籤,它是定義無效的XML。你必須自己解析它,或者修改字符串以使其有效。 – Jonesopolis

+0

如果沒有外部根標記,那麼它是一個無效的xml,如@Jonesopolis所述 – Maddy

+0

此「XML」無效,請參閱https://www.w3.org/TR/REC-xml/#dt-root。但是,如果您需要將其加載到XDocument中,請參閱[使用多個根的C#XDocument加載](https://stackoverflow.com/questions/18186225/c-sharp-xdocument-load-with-multiple-roots)。或者你真的需要反序列化到'List '而不是加載到'XElement'? – dbc

回答

1

試試這個

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 
using System.IO; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string xml = 
       "<person>" + 
        "<name>a</name>" + 
       "</person>" + 
       "<person>" + 
        "<name>b</name>" + 
       "</person>"; 
      xml = "<Root>" + xml + "</Root>"; 

      XDocument doc = XDocument.Parse(xml); 

      List<Person> people = doc.Descendants("person").Select(x => new Person() { 
       Name = (string)x.Element("name") 
      }).ToList(); 
     } 
    } 
    public class Person 
    { 
     public string Name { get; set; } 
    } 
}