tags:

views:

433

answers:

7

I've got a large xml document in a string. What's the best way to determine if the xml is well formed?

+3  A: 

Simply run it through a parser. That will perform the appropriate checks (whether it parses ok).

If it's a large document (as indicated) then an event-based parser (e.g. SAX) will be appropriate since it won't store the document in memory.

It's often useful to have XML utilities around to check this sort of stuff. I use XMLStarlet, which is a command-line set of tools for XML checking/manipulation.

Brian Agnew
+2  A: 

XmlReader seems a good choice as it should stream the data (not load the whole xml in one go)

http://msdn.microsoft.com/en-us/library/9d83k261.aspx

bh213
A: 

Have a look at how-to-deal-with-xml-in-c, which might help you.

tanascius
+1  A: 

Try using an XmlReader with an XmlReaderSettings that has ConformanceLevel.Document set.

dommer
+5  A: 

Something like:

    static void Main() {
        Test("<abc><def/></abc>");
        Test("<abc><def/><abc>");
    }
    static void Test(string xml) {
        using (XmlReader xr = XmlReader.Create(
                new StringReader(xml))) {
            try {
                while (xr.Read()) { }
                Console.WriteLine("Pass");
            } catch (Exception ex) {
                Console.WriteLine("Fail: " + ex.Message);
            }
        }
    }

If you need to check against an xsd, then use XmlReaderSettings.

Marc Gravell
A: 

Save it to an .xml file and open it in Internet Explorer :)

Mladen Mihajlovic
A: 

check this out

Sebastian Sedlak