如何使用C#仅修改XML文件的select参数/属性?
比如说,如果我有一个任意的XML文件,有没有办法只修改某个参数/属性而不更改XML文件的其余部分?例如,让我们举一个简单的例子:如何使用C#仅修改XML文件的select参数/属性?,c#,.net,xml,C#,.net,Xml,比如说,如果我有一个任意的XML文件,有没有办法只修改某个参数/属性而不更改XML文件的其余部分?例如,让我们举一个简单的例子: <?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- The xml file itself contains many other tags --> <ConfigSection> <GeneralParams>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- The xml file itself contains many other tags -->
<ConfigSection>
<GeneralParams>
<parameter key="TableName" value="MyTable1" />
</GeneralParams>
</ConfigSection>
</configuration>
如何将键
TableName
的值更新为“MyTable2”不确定这是最好的方法,但请尝试一下
string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<configuration>
<!-- The xml file itself contains many other tags -->
<ConfigSection>
<GeneralParams>
<parameter key=""TableName"" value=""MyTable1"" />
</GeneralParams>
</ConfigSection>
</configuration>";
var xdoc = XDocument.Parse(xml);
xdoc.Descendants("parameter")
.Single(x => x.Attribute("key").Value == "TableName" && x.Attribute("value").Value == "MyTable1")
.Attributes("value").First().Value = "MyTable2";
stringxml=@”
";
var xdoc=XDocument.Parse(xml);
xdoc.subjects(“参数”)
.Single(x=>x.Attribute(“key”)。Value==“TableName”和&x.Attribute(“Value”)。Value==“MyTable1”)
.Attributes(“value”).First().value=“MyTable2”;
使用XmlDocument还有另一种方法
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<configuration>
<ConfigSection>
<GeneralParams>
<parameter key='TableName' value='MyTable1' />
</GeneralParams>
</ConfigSection>
</configuration>";
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
XmlNode paramter;
XmlNode root = xDoc.DocumentElement;
paramter = xDoc.SelectSingleNode("//parameter/@key");
paramter.LastChild.InnerText = "MyTable2";
string modifiedxml = xDoc.OuterXml;
stringxml=@”
";
XmlDocument xDoc=新的XmlDocument();
LoadXml(xml);
XmlNode参数;
XmlNode root=xDoc.DocumentElement;
parameter=xDoc.SelectSingleNode(“//parameter/@key”);
parameter.LastChild.InnerText=“MyTable2”;
字符串modifiedxml=xDoc.OuterXml;
谢谢你,我的朋友。我需要在某个时候保存XML文档吗?使用<代码> Xdoc。保存< /COD>方法,或者<代码> Xdoc。toSooS/<代码>转换为StrugDy,您认为这个问题是谷歌吗?它每周都会被询问一次,使用微软提供的XmlDocument
和XDocument
库很容易理解。对于1300+代表,您应该更清楚。对于新的实现<代码>XDocument应该是首选。编程模型更好,在提取元素时不需要可怕的强制转换。