How to omit the xml declarations when using XElement.Save?
Asked Answered
O

3

7

XElement.Save actually does what I need but it starts the file with:

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

Is there a way to prevent this?

Should I save using other types, methods after I finish creating my XElement?

Or should I be skipping that line via XmlReader.Read? Because doing this I feel like it's more fragile as I am assuming the first line is always gonna be this xml declaration.

What's the simpliest way to accomplish this?

Omland answered 25/2, 2011 at 23:25 Comment(2)
why do you want to leave that out?Horotelic
Thanks John, now I don't need to I think because your way of reading the xml worked. Otherwise I was getting an error with my method posted in the other question.Omland
S
5

XElement.ToString() won't add the XML declaration to the output. But I don't understand why XmlReader - or any XML parser - would have trouble with a standard XML declaration.

Schumer answered 25/2, 2011 at 23:30 Comment(2)
Thanks, when I used the reader it throws an exception saying, invalid data root, line 1, etc.Omland
I've seen a very similar error caused by the Byte Order Mark at the beginning of the file. Might be worth investigating.Pyromania
C
6

This example writes the example xmlTree data to text file data.xml without a declaration line, yet includes indentation formatting:

XElement xmlTree = new XElement("Root",
  new XAttribute("Attribute1", 1),
  new XElement("Child1", 1),
  new XElement("Child2", 2)
);
using (var writer = XmlWriter.Create("data.xml", new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }))
  xmlTree.Save(writer);
Counterscarp answered 15/10, 2015 at 15:37 Comment(0)
S
5

XElement.ToString() won't add the XML declaration to the output. But I don't understand why XmlReader - or any XML parser - would have trouble with a standard XML declaration.

Schumer answered 25/2, 2011 at 23:30 Comment(2)
Thanks, when I used the reader it throws an exception saying, invalid data root, line 1, etc.Omland
I've seen a very similar error caused by the Byte Order Mark at the beginning of the file. Might be worth investigating.Pyromania
P
3

Using an XmlWriter will give you this ability.

Microsoft article: Serializing with an XML Declaration describes how to control whether serialization generates an XML declaration.

Pegboard answered 25/2, 2011 at 23:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.