[英]Parse xml elements with no root element using Linq in .Net
I have the following xml package that I can't seem to query since it doesn't contain a root element. 我有以下似乎无法查询的xml包,因为它不包含根元素。 Unfortunately, the xml payload can't be changed, so I'm stuck w/ this approach. 不幸的是,xml有效负载无法更改,因此我被这种方法所困扰。 I'm wondering if there's good way to do this with changes to my example. 我想知道是否有一个很好的方法来更改我的示例。 I tried using DesendantsAndSelf as well, but couldn't make it work. 我也尝试使用DesendantsAndSelf,但无法使其正常工作。 Tnx for your help. 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>";
Here's my code example: 这是我的代码示例:
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));
}
This is my class object: 这是我的课程对象:
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; }
}
Simply change XElement element= XElement.Parse(xml);
只需更改XElement element= XElement.Parse(xml);
to var element = XDocument.Parse(xml);
到var element = XDocument.Parse(xml);
. 。 In this case you will get a XDocument
instance, which has a book
descendant. 在这种情况下,您将获得一个XDocument
实例,该实例具有一个book
子代。 If you use XElement element= XElement.Parse(xml);
如果使用XElement element= XElement.Parse(xml);
you current element would be book
which doesn't have any book
descendants. 您当前元素将book
不具有任何book
的后裔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.