[英]Using XMLreader and xpath in large xml-file C#
So I have this rather large XML-file i need to parse and I don't want to load the whole file in memory. 因此,我需要解析这个相当大的XML文件,并且我不想将整个文件加载到内存中。 The XML looks something like this:
XML看起来像这样:
<root>
<node attrib ="true">
<child childattrib=1>
</child>
</node>
<node attrib ="false">
<child childattrib=1>
</child>
</node>
</root>
What I want to do is go through each node named node and see if the attribute matches my search-critera. 我想要做的是遍历每个名为node的节点,看看该属性是否与我的搜索标准匹配。 And I want to do it using xpath.
我想使用xpath做到这一点。 I found Parse xml in c# : combine xmlreader and linq to xml which helps me isolate the node in question.
我在c#中发现了解析xml:将xmlreader和linq合并为xml可以帮助我隔离问题节点。 But I cant use xpath on the parent node.
但是我不能在父节点上使用xpath。 I guess I'll have to create an xmldocument and load the reader, but I cant get it to work the way I want to.
我想我必须创建一个xmldocument并加载阅读器,但是我无法使其按我想要的方式工作。
Attributes need double quotes around value(childattrib). 属性需要在value(childattrib)周围加双引号。 Try following which is a combination of xml reader and xml linq.
请尝试以下是xml阅读器和xml linq的组合。 When reading large xml files always use xmlreader.
读取大型xml文件时,请始终使用xmlreader。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication74
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
while (!reader.EOF)
{
if (reader.Name != "node")
{
reader.ReadToFollowing("node");
}
if (!reader.EOF)
{
XElement node = (XElement)XElement.ReadFrom(reader);
if ((Boolean)node.Attribute("attrib"))
{
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.