簡體   English   中英

在大型xml文件C#中使用XMLreader和xpath

[英]Using XMLreader and xpath in large xml-file C#

因此,我需要解析這個相當大的XML文件,並且我不想將整個文件加載到內存中。 XML看起來像這樣:

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

我想要做的是遍歷每個名​​為node的節點,看看該屬性是否與我的搜索標准匹配。 我想使用xpath做到這一點。 在c#中發現了解析xml:將xmlreader和linq合並為xml可以幫助我隔離問題節點。 但是我不能在父節點上使用xpath。 我想我必須創建一個xmldocument並加載閱讀器,但是我無法使其按我想要的方式工作。

屬性需要在value(childattrib)周圍加雙引號。 請嘗試以下是xml閱讀器和xml linq的組合。 讀取大型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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM