现在的位置: 首页 > 综合 > 正文

C# XmlReader

2013年08月28日 ⁄ 综合 ⁄ 共 9393字 ⁄ 字号 评论关闭

XmlReader在xml文档上提供一种拉样式的API。在.Net Framework中是独一无二的。它可以对xml进行快速的、只向前的只读访问。XmlReader是一个抽象类,其他类派生自它,以提供特定实例,例如XmlTextReader和XmlNodeReader。
 int bookcount = 0;
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreWhitespace = true;
            settings.IgnoreComments = true;

            string booksFile = Server.MapPath("books.xml");
            using (XmlReader reader = XmlReader.Create(booksFile, settings))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element &&
                            "book" == reader.LocalName)
                    {
                        bookcount++;
                    }
                }
            }
            Response.Write(String.Format("Found {0} books!", bookcount));
Reader.LocalName包含节点的非命名空间限定名。Reader.Name属性于它不同包含几点的完全限定名(命名空间)。
System.Xml.Linq命名空间引入了一个新类XDocument,它比XmlDocument友好的多,但仍允许XmlReader和XmlWriter交互操作。
  XDocument booksXML = XDocument.Load(Server.MapPath("books.xml"));

            var books = from book in booksXML.Descendants("{http://example.books.com}book")
                        select book.Element("{http://example.books.com}title").Value;
            Response.Write(String.Format("Found {0} books!", books.Count()));
在验证xml时验证器适用xml实例文档中的schemaLocation提示。如果xml实例文档没有包含查找xml模式的足够信息,实例文档就需要XmlReaderSettings对象上的XmlSchemaSet对象。注意XmlValidatingReader类现在已过时,因为所有的读取器创建都使用XmlReadereate方法进行。
 protected void Page_Load(object sender, EventArgs e)
        {
            int bookcount = 0;
            XmlReaderSettings settings = new XmlReaderSettings();

            string booksSchemaFile = Server.MapPath("books.xsd");

            settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile));
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationFlags =  XmlSchemaValidationFlags.ReportValidationWarnings;
            settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);

            settings.IgnoreWhitespace = true;
            settings.IgnoreComments = true;

            string booksFile = Server.MapPath("books.xml");
            using (XmlReader reader = XmlReader.Create(booksFile, settings))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element &&
                            "book" == reader.LocalName)
                    {
                        bookcount++;
                    }
                }
            }
            Response.Write(String.Format("Found {0} books!", bookcount));
        }

        void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            Response.Write(e.Message);
        }

  XDocument类有一个扩展方法Validate。它把标准的 System.Xml.Schema.XmlSchema对象作为参数,可以根据xml模式验正XDocumnet。
 string booksSchemaFile = Server.MapPath("books.xsd");
        string booksFile = Server.MapPath("books.xml");

        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add(null, XmlReader.Create(booksSchemaFile));
        XDocument booksXML = XDocument.Load(booksFile);
        booksXML.Validate(schemas, (senderParam, eParam) =>
                                   {
                                     Response.Write(eParam.Message);
                                   }, true);

        XNamespace ns = "http://example.books.com";
        var books = from book in booksXML.Descendants(ns + "book")
                    select book.Element(ns + "title").Value;
        Response.Write(String.Format("Found {0} books!", books.Count()));
   XmlReader内部适用NameTable,列出在该文档中使用的所有已知元素、属性、命名空间。这个过程称为原子化,其字面意思是xml被分解为各个原子部分。如果把字符串book作为一个对象引用,和其它元素名一起保存在一个表中,就不需要把book在内部结构中存储次。
  protected void Page_Load(object sender, EventArgs e)
        {
            int bookcount = 0;
        XmlReaderSettings settings = new XmlReaderSettings();

        NameTable nt = new NameTable();
        object book = nt.Add("book");
        settings.NameTable = nt;

        string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd");

        settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile));
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler +=  new ValidationEventHandler(settings_ValidationEventHandler);

        settings.IgnoreWhitespace = true;
        settings.IgnoreComments = true;

        string booksFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml");
        using (XmlReader reader = XmlReader.Create(booksFile, settings))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element &&
                    book.Equals(reader.LocalName)) //A subtle, but significant change!
                {
                    bookcount++;
                }
            }
        }
        Response.Write(String.Format("Found {0} books!", bookcount));

        void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            Response.Write(e.Message);
        }
XmlReader可以适用xml串行化和ReadSubTree提取复杂类型,xml串行化只能串行化对象的公共属性。
[XmlRoot(ElementName = "author", Namespace = "http://example.books.com")]
public class Author
{
    [XmlElement(ElementName = "first-name")]
    public string FirstName;

    [XmlElement(ElementName = "last-name")]
    public string LastName;
}
  protected void Page_Load(object sender, EventArgs e)
        {
         //Create factory early
        XmlSerializerFactory factory = new XmlSerializerFactory();
       
        XmlReaderSettings settings = new XmlReaderSettings();

        NameTable nt = new NameTable();
        object book = nt.Add("book");
        object price = nt.Add("price");
        object author = nt.Add("author");
        settings.NameTable = nt;

        string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, "books.xsd");

        settings.Schemas.Add(null, XmlReader.Create(booksSchemaFile));
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationFlags =  XmlSchemaValidationFlags.ReportValidationWarnings;
        settings.ValidationEventHandler +=   new ValidationEventHandler(settings_ValidationEventHandler);

        settings.IgnoreWhitespace = true;
        settings.IgnoreComments = true;

        string booksFile = Path.Combine(Request.PhysicalApplicationPath, "books.xml");
        using (XmlReader reader = XmlReader.Create(booksFile, settings))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element &&
                   author.Equals(reader.LocalName))
                {
                    //Then use the factory to create and cache serializers
                    XmlSerializer xs = factory.CreateSerializer(typeof(Author));
                    Author a = (Author)xs.Deserialize(reader.ReadSubtree());
                    Response.Write(String.Format("Author: {1}, {0}<BR/>",
                        a.FirstName, a.LastName));
                }
            }
        }
        }

        void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            Response.Write(e.Message);
        }
或者
XDocument booksXML = XDocument.Load(Server.MapPath("books.xml"));
        XNamespace ns = "http://example.books.com";

        var authors = from book in booksXML.Descendants(ns + "author")
                    select new Author
                    {
                        FirstName = book.Element(ns + "first-name").Value,
                        LastName = book.Element(ns + "last-name").Value
                    };
        foreach (Author a in authors)
        {
            Response.Write(String.Format("Author: {1}, {0}<BR/>", a.FirstName, a.LastName));
        }

附:Books.xml
<?xml version='1.0'?>
<!-- This file is a part of a book store inventory database -->
<bookstore xmlns="http://example.books.com"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://example.books.com Books.xsd">
    <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
        <title>The Autobiography of Benjamin Franklin</title>
        <author>
            <first-name>Benjamin</first-name>
            <last-name>Franklin</last-name>
        </author>
        <price>8.99</price>
    </book>
    <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
        <title>The Confidence Man</title>
        <author>
            <first-name>Herman</first-name>
            <last-name>Melville</last-name>
        </author>
        <price>11.99</price>
    </book>
    <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
        <title>The Gorgias</title>
        <author>
            <first-name>Sidas</first-name>
            <last-name>Plato</last-name>
        </author>
        <price>9.99</price>
    </book>
</bookstore>

Books.xsd

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://example.books.com" xmlns="http://example.books.com" targetNamespace="http://example.books.com" elementFormDefault="qualified">
  <xsd:element name="bookstore" type="bookstoreType" />
  <xsd:complexType name="bookstoreType">
    <xsd:sequence maxOccurs="unbounded">
      <xsd:element name="book" type="bookType" />
    </xsd:sequence>
  </xsd:complexType>
  <xsd:complexType name="bookType">
    <xsd:sequence>
      <xsd:element name="title" type="xsd:string" />
      <xsd:element name="author" type="authorName" />
      <xsd:element name="price" type="xsd:decimal" />
    </xsd:sequence>
    <xsd:attribute name="genre" type="xsd:string" />
    <xsd:attribute name="publicationdate" type="xsd:string" />
    <xsd:attribute name="ISBN" type="xsd:string" />
  </xsd:complexType>
  <xsd:complexType name="authorName">
    <xsd:sequence>
      <xsd:element name="first-name" type="xsd:string" />
      <xsd:element name="last-name" type="xsd:string" />
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

抱歉!评论已关闭.