【发布时间】:2019-05-10 00:06:37
【问题描述】:
我有以下似乎无法查询的 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; }
}
【问题讨论】:
-
book是您的根元素。如果您在一个字符串中有多个book元素,只需将其包装在一个虚拟元素中(例如"<root>" + xml + "</root>"; -
这是个好主意。但是如果 book 是根元素,为什么 Linq 查询不能正常工作。因为它没有找到书籍元素。使用 element.Descendants("book") 不正确吗?
-
否,因为在这种情况下,
element是book元素。它没有book类型的后代。