c# 操作xml之xmlReader

xmlReader的名称空间using System.Xml;

xmlReader是通过流的方式来读取xml文件的内容

<?xml version="1.0" encoding="utf-8" ?>
<!--<!-–This file represents a fragment of a book store inventory database-–>-->
<bookstore>
  <book genre="autobiography" publicationdate="1991" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>

</bookstore>

可以通过下面方式来读取<title>元素中的内容

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

namespace xmlTest
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlReader rdr = XmlReader.Create("books.xml");
            while(rdr.Read())
            {
                if(rdr.NodeType == XmlNodeType.Text)
                {
                    string str = rdr.Value;
                }
            }
        }
    }
}

通过设置断点会发现xmlReader是一步一步从xml中读取文件内容的,其中空格、注释等都会读取

原文地址:https://www.cnblogs.com/tianmochou/p/5283911.html