Freigeben über


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:

“<foo></foo><bar></bar>”

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 
    fragment
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ConformanceLevel = ConformanceLevel.Fragment;
//create a reader using the reader settings
XmlReader r = XmlReader.Create(new StringReader(xmlFragmentStr), 
     xrs);
r.Read();

Shayne Burgess

Program Manager | Data Programmability

Comments

  • Anonymous
    September 10, 2008
    PingBack from http://www.easycoded.com/frequently-asked-questions-on-xml-in-net-part-2/

  • Anonymous
    September 11, 2008
    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.

  • Anonymous
    September 15, 2008
    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?

  • Anonymous
    September 17, 2008
    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 :)

  • Anonymous
    September 25, 2008
    Check the Part I and Part II of the Frequently asked questions around XML and .NET integration.

  • Anonymous
    October 07, 2008
    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 :)