微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

修改XML文件的节点属性值


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;

原文地址:https://www.jb51.cc/xml/300560.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。