I have an xml file with the below structure:
<connections>
<connection>
<serverName>serverName1</serverName>
<dbName>dbName1</dbName>
</connection>
</connections>
I have a new connection as text data as shown below:
var xml="<connection><serverName>serverName2</serverName><dbName>dbName2</dbName></connection>";
var xDocument = XDocument.Load(HttpContext.Current.Server.MapPath(this.XmlDataFilePath));
How could I insert this new node to my document?
I tried this but it failed:
xDocument.Root.AddAfterSelf(xml);
xDocument.Save(HttpContext.Current.Server.MapPath(this.XmlDataFilePath));
Thanks,
Parse the XML into an XElement and then add that:
var element = XElement.Parse(xml);
xDocument.Root.Add(element);
Note this is not AddAfterSelf
- you can't add a second root element as the peer of the first one. The code above will add a new child element after any existing ones, within the root element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.