中使用XMLreader和xpath

中使用XMLreader和xpath

本文介绍了在大型xml文件C#中使用XMLreader和xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个相当大的XML文件,我需要解析,而且我不想将整个文件加载到内存中.XML看起来像这样:

So I have this rather large XML-file i need to parse and I don't want to load the whole file in memory. The XML looks something like this:

<root>
    <node attrib ="true">
        <child childattrib=1>
        </child>
    </node>
    <node attrib ="false">
        <child childattrib=1>
        </child>
    </node>
</root>

我想要做的是遍历名为node的每个节点,看看该属性是否与我的搜索标准匹配.我想使用xpath做到这一点.我发现在c#中解析xml:将xmlreader和linq to xml 可以帮助我隔离有问题的节点.但是我不能在父节点上使用xpath.我想我必须创建一个xmldocument并加载阅读器,但是我无法使其按我想要的方式工作.

What I want to do is go through each node named node and see if the attribute matches my search-critera. And I want to do it using xpath.I found Parse xml in c# : combine xmlreader and linq to xml which helps me isolate the node in question. But I cant use xpath on the parent node. 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.

推荐答案

属性需要在value(childattrib)周围加上双引号.请尝试以下方法,它是xml阅读器和xml linq的组合.读取大型xml文件时,请始终使用xmlreader.

Attributes need double quotes around value(childattrib). Try following which is a combination of xml reader and xml linq. When reading large xml files always use 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"))
                    {
                    }
                }
            }

        }

    }
}

这篇关于在大型xml文件C#中使用XMLreader和xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:22