gpt4 book ai didi

c# - 解析这个 xml

转载 作者:太空宇宙 更新时间:2023-11-03 21:37:45 24 4
gpt4 key购买 nike

我尝试了很多代码,但没有任何效果。我有 XML:

<books>
<book>
<title>first title</title>
<publisher>first publisher</publisher>
<description>first description</description>
<published>1410</published>
</book>
<book>
<title>second book</title>
<publisher>second publisher</publisher>
<description>second description</description>
<published>1914</published>
</book>
[another book]
[another book2]
</books>

我想要这样的输入:

first title | first publisher | first description | 1410
second title | second publisher | second descirpion | 1914
[another books]

“我的”代码:

var xdoc = XDocument.Load(@"5.xml");
var entries = from e in xdoc.Descendants("book")
select new
{
Title = (string)e.Element("title"),
Description = (string)e.Element("description")
};
//I DON'T KNOW WHAT IT DO, I FOUND THIS BUT I DON'T KNOW WHAT NEXT

我可以解析第一本书,但无法解析多本书。对不起语言。

最佳答案

如果您想使用 XDocument,您可以尝试以下操作:

using System;
using System.Xml.Linq;

class Program
{
static void Main()
{
var doc = XDocument.Load("5.xml");
var books = doc.Descendants("book");
foreach (var book in books)
{
string title = book.Element("title").Value;
string publisher = book.Element("publisher").Value;
string description = book.Element("description").Value;
string published = book.Element("published").Value;
Console.WriteLine("{0}\t{1}\t{2}\t{3}", title, publisher, description, published);
}
}
}

另一方面,如果您尝试解析的 XML 非常大,无法放入内存,则最好使用 XmlReader,它允许您逐条记录地处理它:

using System;
using System.Xml;

class Program
{
static void Main()
{
using (var reader = XmlReader.Create("5.xml"))
{
string title = null, publisher = null, description = null, published = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "book")
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}", title, publisher, description, published);
}

if (reader.NodeType == XmlNodeType.Element && reader.Name == "title")
{
title = reader.ReadInnerXml();
}

if (reader.NodeType == XmlNodeType.Element && reader.Name == "publisher")
{
publisher = reader.ReadInnerXml();
}

if (reader.NodeType == XmlNodeType.Element && reader.Name == "description")
{
description = reader.ReadInnerXml();
}

if (reader.NodeType == XmlNodeType.Element && reader.Name == "published")
{
published = reader.ReadInnerXml();
}
}
}
}
}

使用这种方法,您可以处理任意大的 XML 文件。

关于c# - 解析这个 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20870109/

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