0

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?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69

2 Answers2

2

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

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

The shortest way is through XDocument:

XDocument doc = new XDocument(
    nex XDeclaration("1.0", "iso-8859-1", "no"),
    XElement.Load(Path)
);
doc.Add(new XComment("Some comment"));

If you want to retain the original, regardless of input, you're going to need XDocument.Load anyway...

MarioDS
  • 12,895
  • 15
  • 65
  • 121
  • This is what I was doing before. The thing is that my `xml` is way too big and is not very efficient creating the whole thing again. – Luis Lavieri Aug 04 '14 at 21:07
  • @LuisLavieri Was efficiency an **actual** problem or was it just you thinking "hmm, tis XML is rather big, must take a long time to load"? Cause I read that XDocument can handle even a few megabytes easily. How big are you talking? – MarioDS Aug 04 '14 at 21:19
  • Is 4 Mb ~70000 lines. But, it is going to grow with time. You are right. I am assuming it. But, is better to avoid any future problems. – Luis Lavieri Aug 04 '14 at 21:25
  • @LuisLavieri not if you worry about things that could never become an issue. If you're confident that the XML will become too big, this is an issue but the issue is the fact that you're using XML to do stuff it just isn't fit for. XML is a stream of information that should be temporary in nature - to transport it between applications for example. If yours is persistent and growing, something much better exists: databases. – MarioDS Aug 04 '14 at 21:29