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

标签 c# .net xml linq xpath

我有以下 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/

相关文章:

java - 为类似的 xml 模式重用 JAXB 类

.net - EF 代码优先 : Methods that can translate to SQL

javascript - E4X规范有误吗?

c# - 使用静态方法和变量——好与坏

c# - 在 C# 中使用数学符号显示方程

.net - 在 .NET 中有效使用功能切换的工具和技术

c# - 关于 MVC 中的 SLUG

xml - Visual Studio 更改调试 xml 命令行参数

c# - ConcurrentDictionary.AddOrUpdate() : Add value to list on update

c# - GridView 仅显示第一个检索到的记录