C# XML基本操作

一 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);
        }
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值