加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

修改XML文件的节点属性值

发布时间:2020-12-16 05:31:36 所属栏目:百科 来源:网络整理
导读:xml 文件内容: ?xml version="1.0" encoding="utf-8"? subtitles info content最新通告:五一放假七天!请各教员悉知/content speed4/speed colorred/color /info /subtitles C#代码: XmlDocument xml = new XmlDocument(); xml.Load(context.Server.MapPath


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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读