Search code examples
c#xmlxmldocumentxmlreader

How to read xml string ignoring header?


I want to read a xml string ignoring the header and the comments.

To ignore the comments it's simples and I found a solution here. But I'm not finding any solution to ignore the header.

Let me give an example:

Consider this xml:

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Some comments -->
<Tag Attribute="3">
    ...
</Tag>

I want to read the xml to a string obtaining just the element "Tag" and others elements but withou the "xml version" and the comments.

The element "Tag" is only an example. Could exist many others.

So, I want only this:

<Tag Attribute="3">
    ...
</Tag>

The code that I've come so far:

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create("...", settings);
xmlDoc.Load(reader);

And I'm not finding anything on XmlReaderSettings to do that.

Do I need to go node by node choosing only the ones I want? This setting does not exist?

EDIT 1: Just to resume my problem. I need the contents of the xml to use in a CDATA of a WebService. When I'm sending comments or xml version, I'm getting an specific error of that part of xml. So I assume that when I read the xml without the version, header and comments I'll be good to go.


Solution

  • Well, it seems that there is no settings to ignore declaration, so I had to ignore it myself.

    Here's the code I've written for those who might be interested:

    private string _GetXmlWithoutHeadersAndComments(XmlDocument doc)
    {
        string xml = null;
    
        // Loop through the child nodes and consider all but comments and declaration
        if (doc.HasChildNodes)
        {
            StringBuilder builder = new StringBuilder();
    
            foreach (XmlNode node in doc.ChildNodes)
                if (node.NodeType != XmlNodeType.XmlDeclaration && node.NodeType != XmlNodeType.Comment)
                    builder.Append(node.OuterXml);
    
            xml = builder.ToString();
        }
    
        return xml;
    }