Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
Iúri dos Anjos Avatar asked Sep 15 '25 02:09

Iúri dos Anjos


1 Answers

Here's a really simple solution.

using (var reader = XmlReader.Create(/*reader, stream, etc.*/)
{
    reader.MoveToContent();
    string content = reader.ReadOuterXml();
}
like image 94
Chris Avatar answered Sep 17 '25 17:09

Chris