I've got this xml file:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<startup><supportedRuntime version="v2.0.50727"/></startup>
<applicationSettings>
<MyApp.Settings>
...
...
</XNet.XManager.Properties.Settings>
</applicationSettings>
I need to replace the <startup>
node with:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
Which is the best way?
If you use LINQ to XML (it's an XML API rather than LINQ):
XDocument doc = XDocument.Load("dat.xml");
XElement startup1 = doc.Root.Element("startup");
startup1.Remove();
doc.Root.Add(new XElement("startup", new XAttribute("useLegacyV2RuntimeActivationPolicy", "true"),
new XElement("supportedRuntime", new XAttribute("version", "v4.0"),
new XAttribute("sku", ".NETFramework"),
new XAttribute("Version", "v4.5.2"))));
doc.Save("dat.xml");
Edit - as Jon Skeet suggested the proper way should be to use XElement.ReplaceWith
:
XDocument doc = XDocument.Load("dat.xml");
XElement startup1 = doc.Root.Element("startup");
startup1.ReplaceWith(new XElement("startup", new XAttribute("useLegacyV2RuntimeActivationPolicy", "true"),
new XElement("supportedRuntime", new XAttribute("version", "v4.0"),
new XAttribute("sku", ".NETFramework"),
new XAttribute("Version", "v4.5.2"))));
doc.Save("dat.xml");
You can use the below code to do the same, where the element is being find and it is replaced with other.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path to your file");
string strXml =
@"<startup useLegacyV2RuntimeActivationPolicy='true'>
<supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.5.2' />
</startup>";
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml = strXml;
xmlDoc.SelectSingleNode("startup").AppendChild(xmlDocFragment);
Update: Using LINQ
. Working Tested Code
var doc = XDocument.Load(@"path to file");
string input = @"<startup useLegacyV2RuntimeActivationPolicy='true'>
<supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.5.2' />
</startup>";
var replacement = XElement.Parse(input);
var nodeToReplace = doc.Descendants().Elements("startup").FirstOrDefault();
nodeToReplace.ReplaceWith(replacement);
doc.Save(@"path to file");
Console.WriteLine(doc);
Console.Read();
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.