Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi all

I have to remove declaration from existing xml using C#
Posted
Updated 14-May-13 2:41am
v3
Comments
ZurdoDev 14-May-13 8:11am    
What's the question?
sharmarun 14-May-13 8:19am    
want to remove

?xml version="1.0" encoding="utf-8" standalone="yes" ?


XML decleration
[no name] 14-May-13 8:25am    
Okay... and? What is the problem with the code that you have written that prevents you from removing that one line of text?
sharmarun 14-May-13 8:29am    
see the code

root = new XElement("AriReport");
xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),root);
xDoc.Element("AriReport").Add(new XAttribute("RowCount", people.Count()));
root.Add(people);


if (!File.Exists(saveLocation))
{
xDoc.Save("C:\\ShoreFollowUp.xml");


}
XDeclaration dec = new XDeclaration("", "", "");
xDoc.Declaration = dec;
xDoc.WriteTo("C:\\ShoreFollowUp.xml");


but this line didnt removed

Hi sharmarun,
Did you check all constructors available for XDocument class? Check here
You need to instance XDocument class with no declaration element/object.

For example:
XDocument doc = new XDocument();
doc.Add(new XComment("This is a comment"));
doc.Add(new XElement("Root", "content"));
Console.WriteLine(doc);


You will have the following output:


XML
<!--This is a comment-->
<Root>content</Root>


Bye.
 
Share this answer
 
v2
An XML file normally has a header line such as you describe - it is optional, but recommended, and XDocument always adds it when you use the Save method.

If it really disturbs you, you need to use an XmlWriter instead - it has an option to turn it off.
C#
XDocument doc = new XDocument(new XElement("MyElement", new XAttribute("MyKey", "MyValue")));
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw, xws))
     {
    doc.Save(xw);
    }
 
Share this answer
 
I would start by understanding XLinq since it is the newest XML technology from Microsoft. There are also other ways of doing it, but probably want to use the newest: XLINQ Introduction Part 3 Of 3[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900