zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# XML基本操作

c#XML 基本操作
2023-09-11 14:16:46 时间

一 XML的内容

在这里插入图片描述

二 XML的处理方式

1 DOM

文档对象模型(Document Object Model)

2 SAX

XML解析的简单API(Simple API for XML)

3 .NET提供了XML支持:System.XML名称空间

三 常用的XML类

1 XmlDocument

.LoadXml() .DocumentElement

2 XmlNode属性

① .ChildNodes .HasChildNodes,.FirstChildNode
② .InnerXml .InnerText .OutterXml .Value
③ .NodeType
④ 子类XmlDocument,XmlElement
.XmlAttribute,XmlEntity

四 XmlNode的操作

1 查询(见Xpath)

2 增加

① AppendChild,PrependChild,
② InsertBefore,InsertAfter

3 删改

RemoveChild,ReplaceChild,RemoveAll;

五 使用XmlTextReader及Writer

1 XmlTextReader

1) 对XML数据进行快速,非缓存,只进访问的读取器

① while(reader.Read())
② switch(reader.NodeType);
③ 使用reader.Name及.Value;

2 XmlTextWriter

① WriteStartElement;
② WriteAttributeString;
③ WriteEndElement等;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;

namespace XmlTextWriter1
{
    internal class Program
    {
        private const string filename = "sampledata.xml";
        static void Main(string[] args)
        {
            XmlTextWriter writer = null;

            writer = new XmlTextWriter(filename, null);


            //为使文件易读,使用缩进
            writer.Formatting = Formatting.Indented;

            //写XML声明
            writer.WriteStartDocument();

            //引用样式
            String PItext = "type='text/xsl' href='book.xsl'";
            writer.WriteProcessingInstruction("xml-stylesheet", PItext);
            //文档类型
            writer.WriteDocType("book", null, null, "<!ENTITY h 'hardcover'>");
            //写入注释
            writer.WriteComment("sample.XML");

            //写一个元素(根元素)
            writer.WriteStartElement("book");

            //属性
            writer.WriteAttributeString("genre", "novel");

            writer.WriteAttributeString("ISBN", "1-8630-014");

            //书名元素
            writer.WriteAttributeString("title", "The Handmaid' s Tale");

            writer.WriteStartElement("style");
            writer.WriteEntityRef("h");

            //价格元素
            writer.WriteElementString("price", "19.95");
            //写入CDATA
            writer.WriteCData("Prices 15% off!");
            //关闭根元素
            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Flush();
            writer.Close();

            //加载文件
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.Load(filename);

            Console.Write(doc.InnerXml);
        }
    }
}