详解通过XmlDocument读写Xml文档的示例代码

黄舟
发布: 2017-03-09 16:53:22
原创
1611人浏览过

通过xmldocument读写xml文档

有如下一段Xml:

<?xml version="1.0" encoding="utf-8" ?>
<students>
  <!--我是一段注释文字-->
  <student name="张平">
    <courses>
      <course name="语文?">
        <teacherComment>
          <![CDATA[
        这里是语文老师的批注
        ]]>
        </teacherComment>      
    </course>

      <course name="数学">
        <teacherComment>
          <![CDATA[
        这里是数学老师的批注
        ]]>
        </teacherComment>
      </course>
    </courses>
  </student>
</students>
登录后复制

1.如何使用XmlDocument读取Xml

我要用一段代码遍历所有Student,并打印Student的所有属性和子节点的值

/*玉开博客 http://www.php.cn/ */
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace XmlExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlFilePath = @"X:\about.net\example\XmlExample\1.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);

            //使用xpath表达式选择文档中所有的student子节点
            XmlNodeList studentNodeList = doc.SelectNodes("/students/student");
            if (studentNodeList != null)
            {
                foreach (XmlNode studentNode in studentNodeList)
                {
                    //通过Attributes获得属性名字为name的属性
                    string name = studentNode.Attributes["name"].Value;
                    Console.WriteLine("Student:" + name);

                    //通过SelectSingleNode方法获得当前节点下的courses子节点
                    XmlNode coursesNode = studentNode.SelectSingleNode("courses");

                    //通过ChildNodes属性获得courseNode的所有一级子节点
                    XmlNodeList courseNodeList = coursesNode.ChildNodes;
                    if (courseNodeList != null)
                    {
                        foreach (XmlNode courseNode in courseNodeList)
                        {
                            Console.Write("\t");
                            Console.Write(courseNode.Attributes["name"].Value);
                            Console.Write("老师评语");
                            //通过FirstNode属性可以获得课程节点的第一个子节点,LastNode可以获得最后一个子节点
                            XmlNode teacherCommentNode = courseNode.FirstChild;
                            //读取CData节点
                            XmlCDataSection cdata = (XmlCDataSection)teacherCommentNode.FirstChild;
                            Console.WriteLine(cdata.InnerText.Trim());
                        }
                    }
                }
            }

            Console.Write("\r\nPress any key to continue....");
            Console.Read();
        }
    }
}
登录后复制

XmlDocument本身是从XmlNode继承的,读Xml节点可以通过FirstChild,LastChild,或者NextSibling,PreviousSibling读取单个节点,或者通过ChildNodes读取所有子节点。还可以使用XPath表达式使用SelectNodes(string xpath)或者SelectSingleNode(string xpath)读取单个或者多个符合条件的节点。

2.如何通过XmlDocument编辑Xml

同样是读取Xml中的xml例子,我们这次要用csharp代码生成xml,如下代码:

/*玉开博客 http://www.php.cn/ */
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace WriteXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //创建Xml声明部分,即<?xml version="1.0" encoding="utf-8" ?>
            xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");

            //创建根节点
            XmlNode rootNode = xmlDoc.CreateElement("students");

            //创建student子节点
            XmlNode studentNode = xmlDoc.CreateElement("student");
            //创建一个属性
            XmlAttribute nameAttribute = xmlDoc.CreateAttribute("name");
            nameAttribute .Value = "张同学";
            //xml节点附件属性
            studentNode.Attributes.Append(nameAttribute);

           
            //创建courses子节点
            XmlNode coursesNode = xmlDoc.CreateElement("courses");
            XmlNode courseNode1 = xmlDoc.CreateElement("course");
            XmlAttribute courseNameAttr = xmlDoc.CreateAttribute("name");
            courseNameAttr.Value = "语文";
            courseNode1.Attributes.Append(courseNameAttr);
            XmlNode teacherCommentNode = xmlDoc.CreateElement("teacherComment");
            //创建Cdata块
            XmlCDataSection cdata = xmlDoc.CreateCDataSection("<font color=\"red\">这是语文老师的批注</font>");
            teacherCommentNode.AppendChild(cdata);
            courseNode1.AppendChild(teacherCommentNode);
            coursesNode.AppendChild(courseNode1);
            //附加子节点
            studentNode.AppendChild(coursesNode);

            rootNode.AppendChild(studentNode);
            //附加根节点
            xmlDoc.AppendChild(rootNode);

            //保存Xml文档
            xmlDoc.Save(@"d:\test.xml");

            Console.WriteLine("已保存Xml文档");


        }
    }
}
登录后复制

使用XmlDocument生成xml的要点在于使用xmlDocument的实例的CreateElement创建XmlNode或者通过CreateAttribute方法创建属性,并通过AppendChild方法附加xml节点,通过AppendAttribute附加Attribute到节点的属性集合。

以上就是详解通过XmlDocument读写Xml文档的示例代码的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号