C# XML文件操作总结 SAX DOM 解析

学习C#之DOM方式操作XML文档 一、XML文档组成 文件头:标记XML版本(固定1.0)和文件编码格式(要按照指定的书写方式(utf-8)) 一个XML文件必须包含一个根节点(根元素),否则文件无效 元素都成对出现,分为开始元素和结束元素。当元素间存在内容时,元素自动分开。当无内容时以出现 XML文件中可以存在任意多个层级的元素操作,放在一对元素之间的并列元素,即为该元素的子节点 开始元素中可以包含任意多个属性用来描述该元素 阅读详情

去年写过一篇关于C# XML文件操作的两种方式,但是没有给出样例代码,这里再次给出两种操作XML文件的方式,并且包含部分样例代码。

以下两种XML操作方式,不仅只是适合C# 语言进行开发,其实语言也都适用。


原文链接: 点击打开链接 http://blog.youkuaiyun.com/weixingstudio/article/details/7026712


1. 解析类型介绍

XML的解析器主要有DOM和SAX两种。

 

先简要介绍SAX解析器(Simple API for XML),其实解析器就是对XML进行处理的一套API,相当于一个模块。

SAX解析器是基于事件处理的,需要从头到尾把XML文档扫描一遍,在扫描的过程中,每次遇到一个语法结构时,就会调用这个特定语法结构的事件处理程序,向应用程序发送一个事件。


XmlReader的类提供了一种非常迅速、只向前的只读光标来处理XML数据,因为它是一个流模型,所以内存要求不是很高。但是,没有提供DOM模型的导航功能和读写功能。

 

DOM是文档对象模型解析,构建文档的分层语法结构,在内存中建立DOM树,DOM树的节点以对象的形式来标识,文档解析文成以后,文档的整个DOM树都会放在内存中。

 

DOM的优点:

1. 当文档的某一部分被多次的访问时,非常方便。

2. 需要对文档进行调整或者一次性的访问整个文档。

3.  DOM可以随时的访问文档中的某个部分。

4. 可以避免一些无效的操作。

 

DOM结构是完全的存储在内存中的,所以如果文档较大的话,会占用大量的内存。

因为XML文档没有大小限制,所以一些文档可能就不能以DOM方式读取,SAX解析则不存在这样的问题,并且SAX解析的速度要比DOM快一些。


2. SAX解析方式


在C#中,使用SAX进行解析的类为XmlReader, XmlWriter,这两个类都是抽象类,由具体的子类来实现相关的功能。

具体的子类: XmlTextReader, XmlTextWriter

接下来简单看看XmlReader的成员:

Methods

 NameDescription
 CloseWhen overridden in a derived class, changes the ReadState to Closed.
 Create(Stream)Creates a new XmlReader instance using the specified stream.
 Create(String)Creates a new XmlReader instance with specified URI.
 Create(TextReader)Creates a new XmlReader instance with the specified TextReader.
 Create(Stream, XmlReaderSettings)Creates a new XmlReader instance with the specified stream and XmlReaderSettings object.
 Create(String, XmlReaderSettings)Creates a new instance with the specified URI and XmlReaderSettings.
 Create(TextReader, XmlReaderSettings)Creates a new XmlReader instance using the specified TextReader and XmlReaderSettings objects.
 Create(XmlReader, XmlReaderSettings)Creates a new XmlReader instance with the specified XmlReader and XmlReaderSettings objects.
 Create(Stream, XmlReaderSettings, String)Creates a new XmlReader instance using the specified stream, base URI, and XmlReaderSettings object.
 Create(Stream, XmlReaderSettings, XmlParserContext)Creates a new XmlReader instance using the specified stream, XmlReaderSettings, and XmlParserContext objects.
 Create(String, XmlReaderSettings, XmlParserContext)Creates a new XmlReader instance using the specified URI, XmlReaderSettings, and XmlParserContext objects.
 Create(TextReader, XmlReaderSettings, String)Creates a new XmlReader instance using the specified TextReader, XmlReaderSettings, and base URI.
 Create(TextReader, XmlReaderSettings, XmlParserContext)Creates a new XmlReader instance using the specified TextReader, XmlReaderSettings, and XmlParserContext objects.
 DisposeReleases the unmanaged resources used by the XmlReader and optionally releases the managed resources.
 Equals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
 FinalizeAllows an Object to attempt to free resources and perform other cleanup operations before theObject is reclaimed by garbage collection. (Inherited from Object.)
 GetAttribute(Int32)When overridden in a derived class, gets the value of the attribute with the specified index.
 GetAttribute(String)When overridden in a derived class, gets the value of the attribute with the specifiedName.
 GetAttribute(String, String)When overridden in a derived class, gets the value of the attribute with the specifiedLocalName and NamespaceURI.
 GetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
 GetTypeGets the Type of the current instance. (Inherited from Object.)
 IsNameGets a value indicating whether the string argument is a valid XML name.
 IsNameTokenGets a value indicating whether or not the string argument is a valid XML name token.
 IsStartElement()Calls MoveToContent and tests if the current content node is a start tag or empty element tag.
 IsStartElement(String)Calls MoveToContent and tests if the current content node is a start tag or empty element tag and if theName property of the element found matches the given argument.
 IsStartElement(String, String)Calls MoveToContent and tests if the current content node is a start tag or empty element tag and if theLocalName and NamespaceURI properties of the element found match the given strings.
 LookupNamespaceWhen overridden in a derived class, resolves a namespace prefix in the current element's scope.
 MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
 MoveToAttribute(Int32)When overridden in a derived class, moves to the attribute with the specified index.
 MoveToAttribute(String)When overridden in a derived class, moves to the attribute with the specifiedName.
 MoveToAttribute(String, String)When overridden in a derived class, moves to the attribute with the specifiedLocalName and NamespaceURI.
 MoveToContentChecks whether the current node is a content (non-white space text, CDATA, Element, EndElement,EntityReference, orEndEntity) node. If the node is not a content node, the reader skips ahead to the next content node or end of file. It skips over nodes of the following type:ProcessingInstruction,DocumentType,Comment, Whitespace, or SignificantWhitespace.
 MoveToElementWhen overridden in a derived class, moves to the element that contains the current attribute node.
 MoveToFirstAttributeWhen overridden in a derived class, moves to the first attribute.
 MoveToNextAttributeWhen overridden in a derived class, moves to the next attribute.
 ReadWhen overridden in a derived class, reads the next node from the stream.
 ReadAttributeValueWhen overridden in a derived class, parses the attribute value into one or moreText,EntityReference, or EndEntity nodes.
 ReadContentAsReads the content as an object of the type specified.
 ReadContentAsBase64Reads the content and returns the Base64 decoded binary bytes.
 ReadContentAsBinHexReads the content and returns the BinHex decoded binary bytes.
 ReadContentAsBooleanReads the text content at the current position as a Boolean.
 ReadContentAsDateTimeReads the text content at the current position as a DateTime object.
 ReadContentAsDecimalReads the text content at the current position as a Decimal object.
 ReadContentAsDoubleReads the text content at the current position as a double-precision floating-point number.
 ReadContentAsFloatReads the text content at the current position as a single-precision floating point number.
 ReadContentAsIntReads the text content at the current position as a 32-bit signed integer.
 ReadContentAsLongReads the text content at the current position as a 64-bit signed integer.
 ReadContentAsObjectReads the text content at the current position as an Object.
 ReadContentAsStringReads the text content at the current position as a String object.
 ReadElementContentAs(Type, IXmlNamespaceResolver)Reads the element content as the requested type.
 ReadElementContentAs(Type, IXmlNamespaceResolver, String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the element content as the requested type.
 ReadElementContentAsBase64Reads the element and decodes the Base64 content.
 ReadElementContentAsBinHexReads the element and decodes the BinHex content.
 ReadElementContentAsBoolean()Reads the current element and returns the contents as a Boolean object.
 ReadElementContentAsBoolean(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as aBoolean object.
 ReadElementContentAsDateTime()Reads the current element and returns the contents as a DateTime object.
 ReadElementContentAsDateTime(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as aDateTime object.
 ReadElementContentAsDecimal()Reads the current element and returns the contents as a Decimal object.
 ReadElementContentAsDecimal(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as aDecimal object.
 ReadElementContentAsDouble()Reads the current element and returns the contents as a double-precision floating-point number.
 ReadElementContentAsDouble(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a double-precision floating-point number.
 ReadElementContentAsFloat()Reads the current element and returns the contents as single-precision floating-point number.
 ReadElementContentAsFloat(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a single-precision floating-point number.
 ReadElementContentAsInt()Reads the current element and returns the contents as a 32-bit signed integer.
 ReadElementContentAsInt(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a 32-bit signed integer.
 ReadElementContentAsLong()Reads the current element and returns the contents as a 64-bit signed integer.
 ReadElementContentAsLong(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as a 64-bit signed integer.
 ReadElementContentAsObject()Reads the current element and returns the contents as an Object.
 ReadElementContentAsObject(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as anObject.
 ReadElementContentAsString()Reads the current element and returns the contents as a String object.
 ReadElementContentAsString(String, String)Checks that the specified local name and namespace URI matches that of the current element, then reads the current element and returns the contents as aString object.
 ReadElementString()Reads a text-only element.
 ReadElementString(String)Checks that the Name property of the element found matches the given string before reading a text-only element.
 ReadElementString(String, String)Checks that the LocalName and NamespaceURI properties of the element found matches the given strings before reading a text-only element.
 ReadEndElementChecks that the current content node is an end tag and advances the reader to the next node.
 ReadInnerXmlWhen overridden in a derived class, reads all the content, including markup, as a string.
 ReadOuterXmlWhen overridden in a derived class, reads the content, including markup, representing this node and all its children.
 ReadStartElement()Checks that the current node is an element and advances the reader to the next node.
 ReadStartElement(String)Checks that the current content node is an element with the given Name and advances the reader to the next node.
 ReadStartElement(String, String)Checks that the current content node is an element with the given LocalName and NamespaceURI and advances the reader to the next node.
 ReadStringWhen overridden in a derived class, reads the contents of an element or text node as a string.
 ReadSubtreeReturns a new XmlReader instance that can be used to read the current node, and all its descendants.
 ReadToDescendant(String)Advances the XmlReader to the next descendant element with the specified qualified name.
 ReadToDescendant(String, String)Advances the XmlReader to the next descendant element with the specified local name and namespace URI.
 ReadToFollowing(String)Reads until an element with the specified qualified name is found.
 ReadToFollowing(String, String)Reads until an element with the specified local name and namespace URI is found.
 ReadToNextSibling(String)Advances the XmlReader to the next sibling element with the specified qualified name.
 ReadToNextSibling(String, String)Advances the XmlReader to the next sibling element with the specified local name and namespace URI.
 ReadValueChunkReads large streams of text embedded in an XML document.
 ResolveEntityWhen overridden in a derived class, resolves the entity reference for EntityReference nodes.
 SkipSkips the children of the current node.
 ToStringReturns a String that represents the current Object. (Inherited from Object.)
Top
Properties

 NameDescription
 AttributeCountWhen overridden in a derived class, gets the number of attributes on the current node.
 BaseURIWhen overridden in a derived class, gets the base URI of the current node.
 CanReadBinaryContentGets a value indicating whether the XmlReader implements the binary content read methods.
 CanReadValueChunkGets a value indicating whether the XmlReader implements the ReadValueChunk method.
 CanResolveEntityGets a value indicating whether this reader can parse and resolve entities.
 DepthWhen overridden in a derived class, gets the depth of the current node in the XML document.
 EOFWhen overridden in a derived class, gets a value indicating whether the reader is positioned at the end of the stream.
 HasAttributesGets a value indicating whether the current node has any attributes.
 HasValueWhen overridden in a derived class, gets a value indicating whether the current node can have aValue.
 IsDefaultWhen overridden in a derived class, gets a value indicating whether the current node is an attribute that was generated from the default value defined in the DTD or schema.
 IsEmptyElementWhen overridden in a derived class, gets a value indicating whether the current node is an empty element (for example,<MyElement/>).
 Item[Int32]When overridden in a derived class, gets the value of the attribute with the specified index.
 Item[String]When overridden in a derived class, gets the value of the attribute with the specifiedName.
 Item[String, String]When overridden in a derived class, gets the value of the attribute with the specifiedLocalName and NamespaceURI.
 LocalNameWhen overridden in a derived class, gets the local name of the current node.
 NameWhen overridden in a derived class, gets the qualified name of the current node.
 NamespaceURIWhen overridden in a derived class, gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
 NameTableWhen overridden in a derived class, gets the XmlNameTable associated with this implementation.
   
 PrefixWhen overridden in a derived class, gets the namespace prefix associated with the current node.
 QuoteCharWhen overridden in a derived class, gets the quotation mark character used to enclose the value of an attribute node.
 ReadStateWhen overridden in a derived class, gets the state of the reader.
 SchemaInfoGets the schema information that has been assigned to the current node as a result of schema validation.
 SettingsGets the XmlReaderSettings object used to create this XmlReader instance.
 ValueWhen overridden in a derived class, gets the text value of the current node.
 ValueTypeGets The Common Language Runtime (CLR) type for the current node.
 XmlLangWhen overridden in a derived class, gets the current xml:lang scope.
 XmlSpaceWhen overridden in a derived class, gets the current xml:space scope. 

整体来说,XmlReader包含了非常多的属性以及函数,足够够我们使用。


我们先给出一个测试用的xml文件:

<?xml version="1.0" encoding="utf-8" ?> 
<!--comment: this file is the book store inventory database, for xml test-->
<bookstroe>
  <book genre="autobiography" publicationdate="1991" ISBN="1-838938-22-0">
    <title>The C# Programming Language</title>
    <author>
      <first-name>Song</first-name>
      <last-name>Wei</last-name>
    </author>
    <price>13.56</price>
  </book>
  <book genre="data structure" publicationdate="2006" ISBN="0-2384823-2-78">
    <title>how to construct your data?</title>
    <author>
      <first-name>Zhang</first-name>
      <last-name>Hua</last-name>
    </author>
    <price>78.03</price>
  </book>
  <book genre="coding" publicationdate="2012" ISBN="1-388928-3-282">
    <title>c++ primer</title>
    <author>
      <first-name>watkins</first-name>
      <last-name>song</last-name>
    </author>
    <price>963.23</price>
  </book>
</bookstroe>


接下来的所有操作都使用这个测试文件进行。


XmlReader的类提供了一种非常迅速、只向前的只读光标来处理XML数据,因为它是一个流模型,所以内存要求不是很高。但是,没有提供DOM模型的导航功能和读写功能。

标准的SAX解析方式是一种推模型,将数据推送的内存,但是C#的SAX解析是一种拉模型,主动的去内存中提取下一个结点数据。


最常用的操作就是XmlReader.Read()函数,这里必须注意,Read()函数会读取所有的Xml文件数据,包括元素的开始,元素的结束,换行符,内容(Text),这些所有的,包括注释,都会读取,所以在使用Read()函数的时候一定要自己判断读取进来的是什么样的结点,通过XmlNodeType进行识别。当读入一个结点之后,还可以判断当前结点是否有属性,也可以使用MoveToContent()函数跳过当前结点的结束,以及空白的Text,自动跳到内容结点,例如开始结点,内容啊神马的。


下面给出通过流模型(SAX)进行读取,查找,写数据等操作。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace XmlTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            XmlReader reader = XmlReader.Create("book.xml");
            richTextBox1.Clear();
            while (reader.Read())
            {
                this.richTextBox1.Text += reader.Name +" "+ reader.AttributeCount+Environment.NewLine;
            }
            reader.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            XmlReader xr = XmlReader.Create("book.xml");
            richTextBox2.Clear();
            while (!xr.EOF)
            {
                if (xr.MoveToContent() == XmlNodeType.Element && xr.Name == "title")
                {
                    this.richTextBox2.Text += xr.ReadElementString() + Environment.NewLine;
                }
                else
                {
                    xr.Read();
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 针对指定的属性查找相关结点以及结点信息
            XmlReader reader = XmlReader.Create("book.xml");
            while (reader.Read())
            {
                if (reader.NodeType==XmlNodeType.Element)
                {
                    if (reader.HasAttributes)
                    {
                        if (reader.GetAttribute("publicationdate")==textBox1.Text.ToString())
                        {
                            MessageBox.Show(reader.GetAttribute("ISBN"));
                        }
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Indent = true;
            xws.NewLineOnAttributes = true;

            XmlWriter xw = XmlWriter.Create("newbook.xml", xws);
            xw.WriteStartDocument();
            xw.WriteStartElement("book");
            xw.WriteAttributeString("genre", "人类探索");
            xw.WriteAttributeString("publicationdate", "2015");
            xw.WriteAttributeString("ISBN", "10-256456-0-45");
            xw.WriteElementString("title", "人类发展史");
            xw.WriteStartElement("author");
            xw.WriteElementString("first-name","aaa");
            xw.WriteElementString("last-name", "bbb");
            xw.WriteEndElement();
            xw.WriteElementString("price", "89");
            xw.WriteEndElement();
            xw.WriteEndDocument();
            xw.Flush();
            xw.Close();
        }
    }
}


看看程序运行结果:



可以看到在构造函数中的Read()函数,在左侧的列表中,首先读取<?xml>这个开始元素,然后获得了当前结点两个属性,接下来读入第一行的回车,判断回车的属性个数为0个,接下来是注释,属性0个,然后是注释的换行符,属性0个,接下来的就比较理解了。


上面的程序中还给出了通过XmlWriter写入Xml数据的方式,XmlWriter提供了只向前的、未缓存的方式进行写入。一定要注意写入的要相匹配,写入一个开始元素,一定要在适当的位置写入结束元素。


        private void button3_Click(object sender, EventArgs e)
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Indent = true;
            xws.NewLineOnAttributes = true;

            XmlWriter xw = XmlWriter.Create("newbook.xml", xws);
            xw.WriteStartDocument();
            xw.WriteStartElement("book");
            xw.WriteAttributeString("genre", "人类探索");
            xw.WriteAttributeString("publicationdate", "2015");
            xw.WriteAttributeString("ISBN", "10-256456-0-45");
            xw.WriteElementString("title", "人类发展史");
            xw.WriteStartElement("author");
            xw.WriteElementString("first-name","aaa");
            xw.WriteElementString("last-name", "bbb");
            xw.WriteEndElement();
            xw.WriteElementString("price", "89");
            xw.WriteEndElement();
            xw.WriteEndDocument();
            xw.Flush();
            xw.Close();
        }

3. DOM解析


DOM解析是在内存中创建一个XML文件的DOM模型,可以方便的对结点进行访问,可以修改结点,添加结点,更加灵活,总体来说,我一般不用SAX进行解析。
DOM解析有个最大的问题就是,XML文件没有大小限制,所以如果你的XML文档太大的话,所有的结点都会加载到内存中。

DOM解析的主要使用的类有: XmlNode,XmlDocument, XmlDataDocument, XmlResolver, XmlNodeList, XmlUrlResolver

对上面的XML数据操作的样例代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace XmlTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            XmlReader reader = XmlReader.Create("book.xml");
            richTextBox1.Clear();
            while (reader.Read())
            {
                this.richTextBox1.Text += reader.Name +" "+ reader.AttributeCount+Environment.NewLine;
            }
            reader.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            XmlReader xr = XmlReader.Create("book.xml");
            richTextBox2.Clear();
            while (!xr.EOF)
            {
                if (xr.MoveToContent() == XmlNodeType.Element && xr.Name == "title")
                {
                    this.richTextBox2.Text += xr.ReadElementString() + Environment.NewLine;
                }
                else
                {
                    xr.Read();
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 针对指定的属性查找相关结点以及结点信息
            XmlReader reader = XmlReader.Create("book.xml");
            while (reader.Read())
            {
                if (reader.NodeType==XmlNodeType.Element)
                {
                    if (reader.HasAttributes)
                    {
                        if (reader.GetAttribute("publicationdate")==textBox1.Text.ToString())
                        {
                            MessageBox.Show(reader.GetAttribute("ISBN"));
                        }
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Indent = true;
            xws.NewLineOnAttributes = true;

            XmlWriter xw = XmlWriter.Create("newbook.xml", xws);
            xw.WriteStartDocument();
            xw.WriteStartElement("book");
            xw.WriteAttributeString("genre", "人类探索");
            xw.WriteAttributeString("publicationdate", "2015");
            xw.WriteAttributeString("ISBN", "10-256456-0-45");
            xw.WriteElementString("title", "人类发展史");
            xw.WriteStartElement("author");
            xw.WriteElementString("first-name","aaa");
            xw.WriteElementString("last-name", "bbb");
            xw.WriteEndElement();
            xw.WriteElementString("price", "89");
            xw.WriteEndElement();
            xw.WriteEndDocument();
            xw.Flush();
            xw.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            // 去掉注释
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            XmlReader reader = XmlReader.Create("book.xml");
            doc.Load(reader);

            // 获取根节点
            XmlNode root = doc.DocumentElement;
            // 遍历所有的直接子节点
            XmlNodeList books = root.ChildNodes;
            foreach (XmlNode node in books)
            {
                // 判断当前结点的属性是否和输入的年一直
                string publicationdate = node.Attributes.GetNamedItem("publicationdate").Value.ToString();
                if (publicationdate==textBox1.Text.Trim())
                {
                    // 当前结点符合搜索的内容
                    // 获取当前结点的子节点信息
                    XmlNode title = node.ChildNodes[0];
                    XmlNode name = node.ChildNodes[1];
                    XmlNode price = node.ChildNodes[2];
                    XmlNode first_name = name.ChildNodes[0];
                    XmlNode last_name = name.ChildNodes[1];

                    string msg = title.InnerText + " " + first_name.InnerText + " " + last_name.InnerText + " " + price.InnerText;
                    MessageBox.Show(msg);
                }
            }
        }
    }
}

同时,C#在查找结点的时候还支持XPath,这个是在查找结点内容或者属性的时候用的非常普遍的查找方式,XPath查找的样例代码,如果想深入了解XPath的相关内容,还请在查找其他相关资料。

        private void button5_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            // 去掉注释
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            XmlReader reader = XmlReader.Create("book.xml");
            doc.Load(reader);

            // 获取根节点
            XmlNode root = doc.DocumentElement;
            XmlNode tofind = root.SelectSingleNode("//book[@publicationdate='" + textBox1.Text.Trim() + "']");
            MessageBox.Show(tofind.Name);
        }


C# XML解析技术案例分析 XML文档是由元素、属性、注释、文本、实体和指令构成的结构化文本。它遵循严格的格式规定,要求正确地开启和关闭标签,并能通过嵌套来表示复杂的数据关系。这种结构化的特性使得XML特别适合描述层级数据和复杂的对象。C#与XML的结合使用在企业级应用程序开发中尤为常见,这是因为XML作为数据交换和存储的格式,具有良好的跨平台特性和强大的数据描述能力。C#语言提供了强大的XML处理能力,这使得开发者可以高效地读取、写入、查询和转换XML数据。本章将深入探讨C#中的XML解析技术,以及不同解析器之间的对比。 阅读详情

相关推荐

HtmlDom解析组件(C#)

用Dom方式解析Html的组件

[C#]_[使用微软OpenXmlSDK (OpenXmlReader)读取xlsx表格]

1.OpenXmlSDK是个很好的类库,可惜只能通过C#调用,C#的童鞋又福气了。 2.服务端程序由于没法安装office,所以这个对asp.net网站来说是最理想的库了。需要.net 4.0版本以上. 3.以流形式,sax模型读取大文件。 using System; using System.Collections.Generic; using System.Linq; using

小白 5989

OpenXmlHelper,其于OpenXml SDK写的帮助类,主要实现Excel的导出、导入的功能及具体的源码Demo(2013-07-17)

OpenXmlHelper,其于OpenXml SDK2.0写的帮助类,主要实现Excel的导出、导入的功能及具体的源码Demo。实现的环境是Visual Studio 2012。 主要修复大于26列时的Bug。

学习C#之SAX方式操作XML文档

使用SAX方式操作XML文档的两个练习, 代码如下:class Program { static void Main(string[] args) { //文件路径 string filePath = @"C:\Users\Administrator\Desktop\C#\File\SaxFile.xml";

骆驼祥子 1142

SAX for .net(sax的适用于.net版)

SAX是Simple API for XML的缩写。 SAX在概念上与DOM完全不同。首先,不同于DOM的文档驱动,它是事件驱动的,也就是说,它并不需要读入整个文档,而文档的读入过程也就是SAX的解析过程……

ERA5数据驱动WRFV4.4实战:单层嵌套配置与关键报错排查指南

本文详细介绍了使用ERA5再分析数据驱动WRFV4.4模式进行单层嵌套模拟的完整实战流程。内容涵盖从数据精准下载、WPS前处理配置、WRF核心参数设置到高频报错的深度排查与解决方案,旨在帮助初学者在有限服务器资源下,高效完成WRF模拟并规避常见陷阱。

q5r6s7的博客 770

C#之XML文件:XML解析

XPath模型的XML文档的节点树。Dom4J(推荐):dom4j是目前在xml解析方面是最优秀的(Hibernate、Sun的JAXM也都使用dom4j来解析XML),它合并了许多超出基本 XML 文档表示的功能,包括集成的 XPath 支持、XML Schema 支持以及用于大文档或流化文档的基于事件的处理。使用DOM4J+XPATH解析XML实践:使用XML实现数据存储,将页面用户提交的数据存储到xml进行持久化,按照分层设计思想,使用Jsp+Servlet实现简单的用户注册系统。

1258

基于单片机的继电器参数测试系统设计

由于原有测试系统在参数设置上过于单一,在对继电器测试过程中需要多次进行器件连接,导致对其测试准确度下降,会造成继电器的二次损伤,基于单片机研究继电器参数测试系统的设计方法。在硬件设计上,构建二级模式集散控制框架,利用单片机进行数据采集和处理,满足实时继电器参数数据的同步控制;设计双极性反向比例输出电路,分别利用电极电阻对继电器两侧电压进行放大,实现继电器实时电压的检测。实验结果:以两组类型断电器为测试对象,分别连接示波器进行真实数据采集,在本文系统的应用下所得参数测试结果,与真实的数据相一致,具有实际应用效

weixin_45905610的博客 1438

C#解析DOM

使用AngleSharp解析DOM,nuget添加引用即可

kaka的专栏 469

IMU660RA姿态解算实战:从传感器滤波到欧拉角输出的完整实现

本文详细介绍了IMU660RA姿态解算的完整实现过程,从传感器滤波到欧拉角输出。通过实战案例和代码示例,展示了如何有效处理陀螺仪和加速度计的噪声问题,并选择合适的算法进行数据融合和姿态解算。特别强调了欧拉角输出中的坐标系对齐和动态补偿技巧,帮助工程师快速掌握IMU660RA的应用。

weixin_42524762的博客 386

STM32H723串口接收全为0 & CAN错误中断问题

STM32H723串口接收全为0 和 叠加的导致CAN错误问题

weixin_38743772的博客 3916

C# XML解析之DOM模型

DOM的工作方式是:首先将XML文档一次性的装入内存,然后根据文档中定义的元素和属性在内存中创建一个“树型结构”也就是一个文档对象模型,这里的含义其实是把文档对象化,文档中每个节点对应着模型中一个对象,而我们都知道对象提供编程接口,所以在Application中我们正是使用这组对象来访问XML文档进而操作XML文档。 下图阐述了Application和DOM交互的过程: DOM在内...

weixin_30617797的博客 275

069、自动曝光(AE)测光策略:全局/中心/点测光与曝光时间增益分配

本文深入探讨了自动曝光(AE)测光策略的技术细节与实际应用。作者通过多个真实案例(手机前置摄像头、车载ADAS、安防监控等)分析了全局测光、中心测光和点测光的优缺点,指出不同场景应采用不同策略。重点剖析了曝光时间与增益分配的"跷跷板效应",提出要根据传感器特性选择最优分配方案。文章强调测光策略应动态调整,并给出5条实用建议:结合场景切换测光模式、关注传感器增益拐点、点测光需防抖处理、全局测光不宜迷信、调试要观察亮度直方图。最后指出AE调试需要结合具体硬件特性进行实测优化,没有通用解决方案。

zzfmlxs的博客 100

C#文件操作 SAX DOM【好文章】

 去年写过一篇关于C# XML文件操作的两种方式,但是没有给出样例代码,这里再次给出两种操作XML文件的方式,并且包含部分样例代码。 以下两种XML操作方式,不仅只是适合C# 语言进行开发,其实语言也都适用。 原文链接: 点击打开链接 http://blog.youkuaiyun.com/weixingstudio/article/details/7026712 1. 解析类型

夏日向日葵的专栏 932

ROM和RAM在单片机程序运行理解

ROM和RAM是电子设备中两种核心存储组件,主要区别在于:ROM用于长期存储系统程序、用户文件等固定数据,断电后数据不丢失,但写入速度较慢;RAM则用于临时存储运行中的程序和数据,读写速度快但断电后数据会清空。在单片机中,ROM存储程序代码和常量,RAM存储运行时的变量和数据。两者协同工作,ROM如同"永久档案库"保存必要信息,RAM则像"临时工作台"支持高速运算,共同确保设备正常运行。

qq_37999850的博客 1618

27、视网膜血管识别与分类的数据集和验证过程

本文介绍了视网膜血管自动识别与分类方法所使用的数据集及其验证过程。通过30张高分辨率的近红外反射视网膜图像,结合专业医生的手动标注结果,构建了包含597个血管段的基准数据集。研究采用准确率、召回率、F1分数和混淆矩阵等评估指标对模型进行验证,并提出了特征增强和分类器优化策略以提升性能。实验结果显示,该方法在复杂区域具有较强的鲁棒性和较高的准确性,为临床应用提供了可靠的依据。

i7j8k9l的博客 148

XML两种解析思想:DOM和SAX

一、什么是XML英文全称为Extensible Markup Language,翻译过来为可扩展标记语言。现实生活中存在着大量的数据,在这些数据之间往往存在一定的关系,我们希望能在计算机中保存和处理这些数据的同时能够保存和处理他们之间的关系。XML就是为了解决这样的需求而产生数据存储格式。在XML语言中,它允许用户自定义标签。每一个标签用于描述一段数据; 一个标签可以分为开始标签和结束标签,在开始

wujingjing_crystal的专栏 3893

机器人视觉联动精度优化:从±2mm到±0.02mm,产线级手眼标定全实战

2025年我接东莞长安Type-C接口分拣项目的时候,就是栽在了手眼标定上:实验室里标定完精度±0.5mm,一到产线直接掉到±2mm,机器人10次有3次抓不住,2000多件Type-C接口直接报废,还撞坏了2套汇川SCARA机器人的吸盘,本来45天的工期拖了3个月,不仅没赚到钱,还倒贴了几万块。手眼标定从来不是简单的跑个demo、算个矩阵就完事了,它是一个系统工程:从硬件选型、安装固定、相机标定、标定流程、算法优化、环境控制、重复验证,每一个环节都会影响最终的联动精度。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 381

c# XML操作 dom sax解析

去年写过一篇关于C# XML文件操作的两种方式,但是没有给出样例代码,这里再次给出两种操作XML文件的方式,并且包含部分样例代码。 以下两种XML操作方式,不仅只是适合C# 语言进行开发,其实语言也都适用。 原文链接: 点击打开链接 http://blog.youkuaiyun.com/weixingstudio/article/details/7026712 1. 解析类型介绍

Go Ahead 1168

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

使用SAX解析XML实例

SA相比DOM有如下好处:不用全部加载完xml后才能开始解析,可以一边加载一便解析,提高效率 package sax;import java.io.File;import java.io.IOException;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser

我的世界我的梦 1449

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

XML的介绍及使用DOM,DOM4J解析xml文件

XML(可扩展标记语言,)是一种用于定义文档结构和数据存储的标记语言。它主要用于在不同的系统之间传输和存储数据。

欢迎来到一个不知名牛马的博客 1276

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

使用SAX解析XML

一、        前言 用 Java解析XML文档,最常用的有两种方法:使用基于事件的XML简单API(Simple API for XML)称为SAX和基于树和节点的文档对象模型(Document Object Module)称为DOM。Sun公司提供了Java API for XML Parsing(JAXP)接口来使用SAX和DOM,通过JAXP,我们可以使用任何与JAXP兼容的XML...

iteye_4939的博客 232

使用TinyXML-2解析XML文件

TinyXML-2 是一个简单、小型、高效的 C++ XML 解析器,可被轻易地集成到其他程序中。它可以实现对XML文件的:创建、解析、修改等功能。本文对xml做了简要介绍,并给出了一个读取并输出xml指定内容的例子。

qq_44667259的博客 4488

XML解析原理分析

XML解析是将XML文档转换为可处理数据结构的过程,涉及到文档结构、解析器类型、解析过程、错误处理等多个方面。理解这些原理有助于有效地使用XML进行数据交换和存储。通过这个示例,我们展示了如何在C#中使用DOM解析XML文档。类提供了丰富的API来处理XML数据,适合于小型和中型XML文档的解析。对于大型XML文档,可能需要考虑使用XmlReader类进行流式解析,以减少内存占用。自定义XML解析通常意味着我们不依赖于现有的XML解析库,而是手动解析XML字符串或文件。

本博客聚焦游戏开发技巧、创业实战心得及大学热门课程干货。这里既有技术深度,也有思维广度,无论你是开发者、创业者还是高校学子,都能在这里找到适合自己的成长之路! 1455

XML DOM

XML DOM:跨语言的XML文档操作接口 XML DOM(文档对象模型)是W3C标准接口,用于以树状结构表示和操作XML文档。它将XML解析为节点树,支持通过编程语言(如JavaScript、C#、Python)动态访问和修改元素、属性及文本内容。 核心特点 树状结构:将XML文档转换为节点层次,支持随机访问。 跨语言支持:JavaScript、Java、C#等均提供DOM实现。 动态操作:可增删改节点,适用于Web开发、数据交换和配置管理。 应用场景 Web开发:通过AJAX解析XML数据。 数据交换:

m0_57545130的博客 908

c# xml dom sax解析记录

Go Ahead 750
上一篇: kmalloc 相关资料总结
下一篇: ZOJ 1004 Anagrams by Stack(dfs堆栈)
watkins
博客等级 码龄18年 1277粉丝 246原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值