1

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>

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.

1 Answer 1

2

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"))
                    {
                    }
                }
            }

        }

    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

So this is a great answer! Thank you! Now, can you point me in i direction where I via xpath can validate if the selected node has attribute = "true"? I tried : var xpathval = node.XPathSelectElement("node[@attrib='true']") but this doesn't return anything
@jdweng, regarding When reading large xml files always use xmlreader. Why is this so? I deal with XML files a fair bit in my line of work and would like to know the reason here. Thanks!
Huge xml files will cause out of memory exceptions using other methods since the entire file is read into memory at one time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.