C# 将 XML 节点替换为新的属性和子节点
本文关键字:属性 子节点 XML 节点 替换 | 更新日期: 2023-09-27 18:34:36
我有这个xml文件:
<?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>
我需要将<startup>
节点替换为:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
哪种方式最好?
如果您使用 LINQ to XML(它是一个 XML API 而不是 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");
编辑 - 正如Jon Skeet建议的那样,正确的方法应该是使用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");
您可以使用以下代码来执行相同的操作,其中查找元素并将其替换为其他元素。
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);
更新:使用 LINQ
.经过工作测试的代码
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();