Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete first line of XML file using XMLDocument in C#?

Tags:

c#

.net

asp.net

People also ask

How do you delete an element in XML?

Remove a Text Node xml is loaded into xmlDoc. Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.

What is the first line of an XML file called?

The first line of an XML document should be a declaration that this is an XML document, including the version of XML being used.

Is <? XML required?

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

What is XmlDocument?

The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. DOM stands for document object model. To read more about it, see XML Document Object Model (DOM).


I don't see why you would want to remove that. But if it is required, you could try this:

XmlDocument doc = new XmlDocument();
doc.Load("something");

foreach (XmlNode node in doc)
{
    if (node.NodeType == XmlNodeType.XmlDeclaration)
    {
        doc.RemoveChild(node);
    }
}

or with LINQ:

var declarations = doc.ChildNodes.OfType<XmlNode>()
    .Where(x => x.NodeType == XmlNodeType.XmlDeclaration)
    .ToList();

declarations.ForEach(x => doc.RemoveChild(x));

I needed to have an XML serialized string without the declaration header so the following code worked for me.

StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings {
    Indent = true,
    OmitXmlDeclaration = true, // this makes the trick :)
    IndentChars = "  ",
    NewLineChars = "\n",
    NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
    doc.Save(writer);
}
return sb.ToString();

Alternatively you can use this;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
    xmlDoc.RemoveChild(xmlDoc.FirstChild);

A very quick and easier solution is using the DocumentElement property of the XmlDocument class:

XmlDocument doc = new XmlDocument();
doc.Load(xmlSourceFile);
Console.Out.Write(doc.DocumentElement.OuterXml);