C# 使用 Linq 为目录中的每个 XML 文件提取单个 XML 属性

发布于 2024-09-01 12:42:08 字数 126 浏览 4 评论 0原文

如何使用 Linq 从目录中的每个 XML 文件中提取单个 XML 属性,并将该元素放入 C# 列表中。我必须逐个循环遍历每个文件吗? XML 文件非常大,因此我想在不将整个文件加载到内存中的情况下执行此操作。

谢谢, j

How do I use Linq to extract a single XML attribute form each XML file in a directory and put that element in a C# list. Do I have to loop thru each file one-by-one? The XML files are quite large so I'd like to do this without loading the entire file into memory.

Thanks,
j

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鼻尖触碰 2024-09-08 12:42:08

除非文件很大(100 MB 以上),否则我无法拒绝这段代码的优雅:

var result = Directory.GetFiles(filePath)
    .Select(path => XDocument.Load(path))
    .Select(doc => doc.Root.Element("A").Attribute("B").Value)
    .ToList();

我真的希望您的 XML 文件没有那么大...

Unless the files are massive (100 MB+) I would be unable to turn down the elegance of this code:

var result = Directory.GetFiles(filePath)
    .Select(path => XDocument.Load(path))
    .Select(doc => doc.Root.Element("A").Attribute("B").Value)
    .ToList();

I really hope your XML files are not that big though...

知足的幸福 2024-09-08 12:42:08

您确实必须遍历每个文件,这意味着至少要解析每个文件的足够 XML 内容才能获取所需的属性。

XDocument(即 LINQ to SQL)将在每种情况下解析并加载完整文档,因此您最好直接使用 XmlReader 实例。这将需要更多的工作:您必须读取 XML 节点,直到找到正确的节点,并跟踪您所在的位置。

You do have to go through every file, and this will mean at least parsing enough of the XML content of each file to get to the required attribute.

XDocument (i.e. LINQ to SQL) will parse and load the complete document in each case, so you might be better using an XmlReader instance directly. This will require more work: you will have to read the XML nodes until you get to the right one, keeping track of where you are.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文