Click here to Skip to main content
15,914,419 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hello. I have an XML:

XML
<connectionStrings>
  <add name="networkingEntities" connectionString="bla"/>
  <add name="networkingEntitiesAdmin" connectionString="blabla"/>
  <add name="FtpConnection" connectionString="blabla" />
</connectionStrings>


I want to add at the begining and at the end "configuration" and "/configuration"

and then in another method to be able to remove those 2.

Can you please help?

I haven't worked with xml never...
Thank you

Tried this but...I get and error :

C#
XmlDocument doc = new XmlDocument();
          doc.Load(filename);
          XmlElement fileElement = doc.CreateElement("configuration");
          XmlElement rootElement = (XmlElement)doc.SelectSingleNode("/Root");
          rootElement.AppendChild(fileElement);

          doc.Save(filename);
Posted
Updated 19-Jun-13 4:32am
v3
Comments
Mahesh Bailwal 19-Jun-13 10:35am    
what error are you getting?
Luci C 19-Jun-13 10:39am    
"Object reference not set to an instance of an object." it's because the rootelement doesn't instantiate

If I remove that cast it give me " Cannot implicitly convert xml node to xml element"

1 solution

As per my understanding you can not add anything in XML file using XmlDocument outside the root element and which is <connectionStrings>. Other way to do that is to use File handling. Below is sample
string xml = File.ReadAllText(filename);
      xml = "<configuration>" + xml + "</configuration>";
      File.WriteAllText(filename, xml);
 
Share this answer
 
Comments
Luci C 19-Jun-13 10:57am    
great...it works
Now, how can I remove those?
Mahesh Bailwal 20-Jun-13 1:41am    
For removing you can use below code

string xml = File.ReadAllText(filename);
xml = xml.Replace("<configuration>", "").Replace("</configuration>", "");
File.WriteAllText(filename, xml);

Please mark it solved if it worked for you.

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