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

解析XML【C#】



XML节点(Node)与元素(Element):

节点可以是一个元素节点、属性节点、文本节点、注释节点或任何其他DOM中定义的节点类型;

元素(是一种节点)可包含属性,其他元素或文本。如果元素含有文本,则在文本节点中表示该文本。注意:文本永远存储在文本节点中。即使最简单的元素节点也拥有文本节点。举例:在<year>2005</year>中,有一个元素节点<year>,同时此节点之下存在一个文本节点,其中含有文本“2005”。

1.XML元素
XML元素包含一个标记、元素中的数据标记
例如:<book>book name</book>
其中 book是元素名称、book name是元素数据
元素名称区分大小写
一个XML文档中必须有一个根元素
2.XML属性
属性添加在元素的开标记
<book titile = "book name"></book>或者<book title = 'book name'></book>
属性的值可以用双引号也可以用单引号
3.元素与属性举例
<book><title>book name</title></book>
<book title = "book name"></book>
上述两种没有本质的区别,但使用时建议使用第一种,因为可以对元素增加属性或子元素,但是不能这样操作属性
4.XML读取解析
DOM解析XML文档:XML的文档结构是个树状结构
DOM的类在System.Xml中
XmlDocument:用于加载XML文件存放的磁盘位置
XmlNode:这个类表示文档树中的一个节点
XmlNodeList:表示一个节点的集合
XmlElement:表示XML文档中的一个元素
XmlAttribute:表示XML的一个属性
XmlText:表示开标记和闭标记间的文本
(1)XmlDocument:加载xml文档
例:XmlDocument document = new XmlDocument();
document.load(@"D:\C#\books.xml");
(2)XmlElement:用于返回一个元素实例
XmlElement element = document.DocumentElement; //常用来返回一个根节点
XmlElement类包含许多方法属性,可以处理树的节点和属性
1)FirstChild:返回根元素节点后的第一个子节点
2)LastChild:返回根元素节点后的最后一个子节点
3)ParentNode:返回当前元素的父节点
4)NextSibling:返回当前节点的父节点下的下一个节点
5)HasChildNodes:用来检查当前元素是否有子元素
(3)XmlText:表示开关标记间的文本,是特殊的节点,属性有:
1)InnerText:获取当前节点范围内的所有子节点的文本连接起来的字符串
2)InnerXml:获取当前节点范围内的所有子节点的文本连接起来的字符串,包含标记
5.XML修改解析
(1)创建节点

创建节点方法
1)CreateElement:用来创建XMLDocument类型的节点
2)CreateAttribute:用来创建XMLAttribute类型的节点
3)CreateTextNode:用来创建XMLTextNode类型的节点
4)CreateNode:用来创建任意类型的节点,包含上述三种以及其他
创建节点后添加操作:
1)AppendChild:把创建的节点类型追加到XmlNode类型或其他派生类型的节点后
2)InsertAfter:将新节点插入到特定的位置
3)InsertBefore:将新节点插入到特定位置
(2)删除节点
1)RemoveChild:删除当前节点范围内的一个指定的子节点
2)RemoveAll:删除该节点范围内的所有子节点
(3)修改节点
1)ReplaceChild:用新子节点替换旧子节点
6.XML查询解析
(1)使用XmlDocument 方法

XmlDocument document = new XmlDocument();
document.Load(filePath);
XmlNodeList list = document.GetElementsByTagName("book");
foreach (XmlNode node in list)
{
listBox1.Items.Add(node.Name);//listBox1类型是ListBox
}
(2)使用XPath选择特定的节点的方法
1)SelectSingleNode:用来选择一个节点,如果有多个,则返回第一个节点
2)SelectNodes:返回一个节点的集合,类型是XmlNodesList
选择特定的节点的方法参数XPath
XPath是XML文档的查询语言

7.XML解析代码

<span style="font-family:KaiTi_GB2312;font-size:18px;">using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace Update
{
    public partial class Form1 : Form
    {

        string filePath = Directory.GetCurrentDirectory() + @"\uploadXML.xml";
        public Form1()
        {
            InitializeComponent();
        }

        //读取xml
        private void button1_Click(object sender,EventArgs e)
        {

            if (File.Exists(filePath))
            {

                XmlDocument document = new XmlDocument();
                document.Load(filePath);
                XmlNode root = (XmlNode)document.DocumentElement;
                //循环展示成树状
                xmlProcess(root,0);

            }
          
        }
        

        /*
         * 循环展示成树状
         */
        private void xmlProcess(XmlNode root,int i) 
        {

            if (root == null) 
            {
                return;
            }
            if (root is XmlElement) 
            {
                listBox1.Items.Add(root.Name.PadLeft(root.Name.Length + i));
                if (root.HasChildNodes) 
                {
                    xmlProcess(root.FirstChild,i+2);
                }
                if (root.NextSibling != null) 
                {
                    xmlProcess(root.NextSibling,i);
                }

            }
            else if (root is XmlText) 
            {
                string text = ((XmlText)root).Value;
                listBox1.Items.Add(text.PadLeft(text.Length+i));
            }
        }

        //读取文本节点
        private void button2_Click(object sender,EventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load(filePath);
            XmlNode root = (XmlNode)document.DocumentElement;
            string values = root.InnerText;
            string values2 = root.InnerXml;
            string values3 = root.Value;
            MessageBox.Show(values);
            MessageBox.Show(values2);
            MessageBox.Show(values3);
        }
        //添加节点
        private void button3_Click(object sender,EventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load(filePath);
            XmlElement root = document.DocumentElement;

            //create node
            XmlElement newBook = document.CreateElement("book");
            XmlElement newTitle = document.CreateElement("title");
            XmlElement newAuthor = document.CreateElement("author");
            
            //create text
            XmlText titleText = document.CreateTextNode("new title");
            XmlText authorText = document.CreateTextNode("new author");

            //insert
            newTitle.AppendChild(titleText);
            newAuthor.AppendChild(authorText);

            newBook.AppendChild(newTitle);
            newBook.AppendChild(newAuthor);

            root.AppendChild(newBook);

            //save
            document.Save(filePath);




        }
        //删除节点
        private void button4_Click(object sender,EventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load(filePath);
            XmlElement root = document.DocumentElement;
            if (root.HasChildNodes) 
            {
                XmlNode old = root.LastChild;
                root.RemoveChild(old);
            }

            document.Save(filePath);

        }
        //修改节点
        private void button5_Click(object sender,EventArgs e)
        {
            XmlDocument document = new XmlDocument();
            document.Load(filePath);
            XmlElement root = document.DocumentElement;
            if (root.HasChildNodes)
            {
                XmlNode oldNode = root.LastChild;
                XmlNode newNode = document.CreateElement("Book");
                root.ReplaceChild(newNode,oldNode);
            }

            document.Save(filePath);

        }
        //查询节点
        private void button6_Click(object sender,EventArgs e)
        {
            listBox1.Items.Clear();

            XmlDocument document = new XmlDocument();
            document.Load(filePath);
            XmlNodeList list = document.GetElementsByTagName("book");//要查询的的节点名
            foreach (XmlNode node in list) 
            {
                listBox1.Items.Add(node.Name);
            }
        }

    }
}
</span>

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