当前位置: 移动技术网 > IT编程>开发语言>.net > XML文件修改节点属性值(多种方法)

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

村上里沙与金毛,金复新,许楚辉

xml 文件内容:
复制代码 代码如下:

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

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

xmldocument xml = new xmldocument();
xml.load(context.server.mappath("~/js/xmlfile.xml"));
xmlnode xn = xml.documentelement;
foreach (xmlnode node in xn.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字符串的某个节点的属性值,如下:
复制代码 代码如下:

xmldocument doc = new xmldocument();
doc.loadxml("<fsdlconfig username=\"ss\" password=\"134\"/>");
xmlattribute att =(xmlattribute)doc.selectsinglenode("/fsdlconfig/@username");
console.writeline(att.value);
att.value = "test";
string str = doc.outerxml;

节点username的值由原来的"ss",变成了"test",然后用doc.outerxml保存修改后的xml为字符串。
另一种方式
复制代码 代码如下:

xmldocument doc = new xmldocument();
doc.loadxml("<fsdlconfig username=\"ss\" password=\"134\"/>");
xmlelement att = (xmlelement)doc.firstchild;
att.setattribute("username","test");
string str = doc.outerxml;

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网