Search code examples
c#.netxmllinq-to-xmlxmlreader

Detect XML fragments in C#


Is there a reliable way to detect in C#/.NET whether a given piece of XML is rooted XML content or a non-rooted fragment?

Rooted content:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <a>a</a>
</root>

Fragment:

<a>a</a>
<b>b</b>
<c>c</c>

I'm trying to identify these situations using the XmlReader and XDocument classes but I can't really distinguish between ordinary XmlExceptions and the one thrown when trying to load an otherwise valid fragment.


Solution

  • If you want to use XmlReader, you can do it like this:

    static bool IsXmlRooted(Stream st) {
        bool sawRoot = false;
        using (var reader = XmlReader.Create(st, new XmlReaderSettings() {
            // fragment works for documents too
            ConformanceLevel = ConformanceLevel.Fragment
        })) {
            while (reader.Read()) {
                // if we see element at depth 0 - it's top-level element
                if (reader.NodeType == XmlNodeType.Element && reader.Depth == 0) {
                    // if we already saw another top level element - that is fragment
                    // can return fast
                    if (sawRoot)
                        return false;
                    sawRoot = true;
                }
            }
        }
        return true;
    }