Frequently Asked Questions on XML in .NET – Part 2

This is the next post in our ongoing FAQ series. See the original post here.

Q2: Conformance Level – Fragment

There are times when you want to work with a piece of XML that is not a fully conformant xml document; an example of this is when the XML does not have one root element. This type of XML is called an XML fragment. Here is an example of an XML fragment:


If this snippet of XML is used as the source for to the XmlReader, the following exception will occur:

“There are multiple root elements. Line X, position Y.”

This is a good exception message and tells the user exactly what the problem is: more than one root element is not allowed in an XML document. But what happens if you really want to work with XML of this form? A flag in the XmlReaderSettings class is provided for exactly this situation: XmlReaderSettings.ConformanceLevel.

Code snippet to correctly read the XML fragment:

string xmlFragmentStr = "<foo></foo><bar></bar>";
//create a reader settings objects and set the conformance level to
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ConformanceLevel = ConformanceLevel.Fragment;
//create a reader using the reader settings
XmlReader r = XmlReader.Create(new StringReader(xmlFragmentStr),

Shayne Burgess

Program Manager | Data Programmability

Comments (6)

  1. Guy Ellis says:

    Very cool – thanks for posting this. I didn’t know about the ConformanceLevel.Fragment flag/option and have always in the past wrapped the fragment in an artificial root such as "<root>" + fragment + "</root>" but this is way better.

  2. Doug Domeny says:

    Thanks. This is the sort of information that is very helpful.

    For XSL transforms, I’ve always tried it and if it fails, wrapped the source in <root> tags (just like Guy). But this, of course, doesn’t work if the XML is in file or stream rather than a string.

    Is there a corresponding ConformanceLevel property for transforms or would it still work?

  3. Skyler says:

    Very nice.  I’ve been using XML as a convenient protocol for IPC and was running into an issue where multiple messages would queue up, hence creating a fragment that the reader couldn’t handle!  This completely solves that 🙂

  4. Check the Part I and Part II of the Frequently asked questions around XML and .NET integration.

  5. Dennis says:

    When will we see a new drop of LinqToXSD? I love this module, don’t have to think about XML at all, things just work 🙂

Skip to main content