zl程序教程

您现在的位置是:首页 >  其他

当前栏目

XML文件修改节点属性值(多种方法)

2023-06-13 09:14:51 时间
xml文件内容:
复制代码代码如下:

<?xmlversion="1.0"encoding="utf-8"?>
<subtitles>
<info>
<content>最新通告:五一放假七天!请各教员悉知</content>
<speed>4</speed>
<color>red</color>
</info>
</subtitles>

C#代码:
复制代码代码如下:

XmlDocumentxml=newXmlDocument();
xml.Load(context.Server.MapPath("~/js/XMLFile.xml"));
XmlNodexn=xml.DocumentElement;
foreach(XmlNodenodeinxn.ChildNodes)
{
if(node.Name=="info")
{
node["content"].InnerText=content;
node["speed"].InnerText=speed;
node["color"].InnerText=color;
}
}
xml.Save(context.Server.MapPath("~/js/XMLFile.xml"));

另外两种办法:
修改xml字符串的某个节点的属性值,如下:
复制代码代码如下:
XmlDocumentdoc=newXmlDocument();
doc.LoadXml("<fsdlconfiguserName=\"ss\"password=\"134\"/>");
XmlAttributeatt=(XmlAttribute)doc.SelectSingleNode("/fsdlconfig/@userName");
Console.WriteLine(att.Value);
att.Value="test";
stringstr=doc.OuterXml;

节点userName的值由原来的"ss",变成了"test",然后用doc.OuterXml保存修改后的xml为字符串。
另一种方式
复制代码代码如下:
XmlDocumentdoc=newXmlDocument();
doc.LoadXml("<fsdlconfiguserName=\"ss\"password=\"134\"/>");
XmlElementatt=(XmlElement)doc.FirstChild;
att.SetAttribute("userName","test");
stringstr=doc.OuterXml;