gpt4 book ai didi

c# - 在.Net中使用Linq解析没有根元素的xml元素

转载 作者:行者123 更新时间:2023-12-02 02:03:12 25 4
gpt4 key购买 nike

我有以下 xml 包,我似乎无法查询它,因为它不包含根元素。不幸的是,xml 有效负载无法更改,所以我陷入了这种方法。我想知道是否有好的方法可以通过更改我的示例来做到这一点。我也尝试使用 DesendantsAndSelf,但无法使其工作。感谢您的帮助。

    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 后代。

关于c# - 在.Net中使用Linq解析没有根元素的xml元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56069076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com