Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a 'fake' xml document (xml fragment) in a XmlTextReader object

[Case] I have reveived a bunch of 'xml files' with metadata about a big number of documents in them. At least, that was what I requested. What I received where 'xml files' without a root element, they are structured something like this (i left out a bunch of elements):

<folder name = "abc"></folder>
<folder name = "abc/def">
<document name = "ghi1">
</document>
<document name = "ghi2">
</document>
</folder>

[Problem] When I try to read the file in an XmlTextReader object it fails telling me that there is no root element.

[Current workaround] Of course I can read the file as a stream, append < xmlroot> and < /xmlroot> and write the stream to a new file and read that one in XmlTextReader. Which is exactly what I am doing now, but I prefer not to 'tamper' with the original data.

[Requested solution] I understand that I should use XmlTextReader for this, with the DocumentFragment option. However, this gives the compiletime error:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: XmlNodeType DocumentFragment is not supported for partial content parsing. Line 1, position 1.

[Faulty code]

using System.Diagnostics;
using System.Xml;

namespace XmlExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"C:\test.txt";
            XmlTextReader tr = new XmlTextReader(file, XmlNodeType.DocumentFragment, null);
            while(tr.Read())
                Debug.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);
        }
    }
}
like image 407
Martijn Burger Avatar asked Jan 21 '26 20:01

Martijn Burger


1 Answers

This works:

using System.Diagnostics;
using System.Xml;

namespace XmlExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"C:\test.txt";
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;
            using (XmlReader reader = XmlReader.Create(file, settings))
            {
                while (reader.Read())
                    Debug.WriteLine("NodeType: {0} NodeName: {1}", reader.NodeType, reader.Name);
            }
        }
    }
}
like image 120
Martijn Burger Avatar answered Jan 24 '26 18:01

Martijn Burger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!