xenos xenos - 3 months ago 9
C# Question

How can I remove the first element of XML using c#?

I need to remove the first element.
I have the XmlDocument doc which has this xml. Just need to know how to remove the first element "?xml version="1.0" encoding="US-ASCII"?".

This needs to be

<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/*">
<xsl:apply-templates select="*[1]"/>
</xsl:template>
<xsl:template match="@*|node()"><!--identity for all other nodes-->
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>


like this

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/*">
<xsl:apply-templates select="*[1]"/>
</xsl:template>
<xsl:template match="@*|node()"><!--identity for all other nodes-->
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

Answer

If you have an XmlDocument object containing the XML, then you can get the XML without the XML declaration like this:

string xml = doc.DocumentElement.OuterXml;

Alternatively, you can remove the XmlDeclaration completely:

if (doc.FirstChild is XmlDeclaration)
    doc.RemoveChild(doc.FirstChild);
string xml = doc.OuterXml;