[英]Parse xml elements with no root element using Linq in .Net
我有以下似乎无法查询的xml包,因为它不包含根元素。 不幸的是,xml有效负载无法更改,因此我被这种方法所困扰。 我想知道是否有一个很好的方法来更改我的示例。 我也尝试使用DesendantsAndSelf,但无法使其正常工作。 Tnx为您提供帮助。
string xml = @"<book number='3'>
<description>Test</description>
<chapter number='3-1-1'>
<description>Test</description>
</chapter>
<chapter number='3-1-2'>
<description>Test</description>
</chapter>
</book>";
这是我的代码示例:
XElement element= XElement.Parse(xml);
List<Book> books = ( from t in element.Descendants("book")
select new Book
{
number = (String)t.Attribute("number"),
description = (String)t.Element("description").Value,
// Load the chapter information
chapters = t.Elements("chapter")
.Select(te => new Chapter
{
number = (String)te.Attribute("number"),
description = (String)t.Element("description").Value
}).ToList(),
}).ToList();
foreach(var d in books)
{
Console.WriteLine(String.Format("number = {0}: description = {1}",d.number,d.description));
foreach(var c in d.chapters)
Console.WriteLine(String.Format("number = {0}: description = {1}",c.number,c.description));
}
这是我的课程对象:
public class Book
{
public String number { get; set; }
public String description { get; set; }
public List<Chapter> chapters { get; set; }
}
public class Chapter
{
public String number { get; set; }
public String description { get; set; }
}
只需更改XElement element= XElement.Parse(xml);
到var element = XDocument.Parse(xml);
。 在这种情况下,您将获得一个XDocument
实例,该实例具有一个book
子代。 如果使用XElement element= XElement.Parse(xml);
您当前元素将book
不具有任何book
的后裔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.