A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-8-7 18:36  /  708 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

有关XML文件的节点属性值修改在使用过程中经常会遇到过,感兴趣的朋友可以参考下本文,希望对你有所帮助
xml 文件内容:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <subtitles>
  3. <info>
  4. <content>最新通告:五一放假七天!请各教员悉知</content>
  5. <speed>4</speed>
  6. <color>red</color>
  7. </info>
  8. </subtitles>
复制代码

C#代码:

  1. XmlDocument xml = new XmlDocument();
  2. xml.Load(context.Server.MapPath("~/js/XMLFile.xml"));
  3. XmlNode xn = xml.DocumentElement;
  4. foreach (XmlNode node in xn.ChildNodes)
  5. {
  6. if (node.Name == "info")
  7. {
  8. node["content"].InnerText = content;
  9. node["speed"].InnerText = speed;
  10. node["color"].InnerText = color;
  11. }
  12. }
  13. xml.Save(context.Server.MapPath("~/js/XMLFile.xml"));
复制代码

另外两种办法:
修改xml字符串的某个节点的属性值,如下:

  1. XmlDocument doc = new XmlDocument();
  2. doc.LoadXml("<fsdlconfig userName=\"ss\" password=\"134\"/>");
  3. XmlAttribute att =(XmlAttribute)doc.SelectSingleNode("/fsdlconfig/@userName");
  4. Console.WriteLine(att.Value);
  5. att.Value = "test";
  6. string str = doc.OuterXml;
复制代码

节点userName的值由原来的"ss",变成了"test",然后用doc.OuterXml保存修改后的xml为字符串。
另一种方式

  1. XmlDocument doc = new XmlDocument();
  2. doc.LoadXml("<fsdlconfig userName=\"ss\" password=\"134\"/>");
  3. XmlElement att = (XmlElement)doc.FirstChild;
  4. att.SetAttribute("userName","test");
  5. string str = doc.OuterXml;
复制代码



0 个回复

您需要登录后才可以回帖 登录 | 加入黑马