Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if XML is well formed?

Tags:

c#

xml

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

like image 858
PaulB Avatar asked Apr 08 '09 08:04

PaulB


3 Answers

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

like image 77
dommer Avatar answered Sep 28 '22 01:09

dommer


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.

like image 45
Marc Gravell Avatar answered Sep 28 '22 01:09

Marc Gravell


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.

like image 27
Brian Agnew Avatar answered Sep 28 '22 02:09

Brian Agnew