Search code examples
c#xmlxelement

Save XElement without affecting the current header


So, I'm loading the XElement of a document like this:

Root = XElement.Load(Path);

The original header looks like this:

<?xml version="1.0" encoding="iso-8859-1"?>
<!--Some comment -->

When I call Root.Save("file.xml"); it changes the header declaration and erases the comment. Why is this happening? What can I do besides creating a new whole xml with XDocument to avoid this?


Solution

  • use XDocument.Load instead of XElement.Load.

    XML declarations are belong to XDocument not XElement. XElement is just loads Root element.See this and this for more details