Home  >  Article  >  Backend Development  >  Detailed code explanation of three implementation methods of C# reading XML

Detailed code explanation of three implementation methods of C# reading XML

黄舟
黄舟Original
2017-03-06 11:14:042546browse

XML file is a commonly used file format. This article mainly introduces three implementation methods for C# to read XML, mainly XmlDocument, XmlTextReader, and Linq to Xml. Those who are interested can learn more.

Preface

XML file is a commonly used file format, such as app.config in WinForm and web.config in Web programs It is found in documents and many important places. (Similar to Json) Microsoft also provides a series of class libraries to help us store XML files in applications.

There are generally two models for accessing and operating XML files in programs:

DOM (Document Object Model):The benefits of using DOM are that it allows editing and updating of XML documents, random access to data in the document, and XPath querying, but The disadvantage of DOM is that it needs to load the entire document into memory at once, which can cause resource problems for large documents.

Stream model:The stream model solves this problem very well, because it uses the concept of stream to access XML files, that is to say, only the current node, but it also has its shortcomings, it is read-only, forward-only, and cannot perform backward navigation operations in the document.

The three methods of reading XML files in C# are as follows:

1. Use XmlDocument (DOM mode)

2 .Use XmlTextReader (stream mode)

3.Use Linq to Xml (Linq mode)

Use XmlDocument mode to read

Using XmlDocument is a way to read XML files based on the document structure model. In an XML file, we can think of XML as consisting of a document declaration (Declare), an element (Element), and an attribute (Attribute). , a tree composed of text (Text), etc. The first node is called the root node, and each node can have its own child nodes. After getting a node, it can be obtained through a series of attributes or methods The value of this node or some other attributes. For example:

xn 代表一个结点
xn.Name;//这个结点的名称
xn.Value;//这个结点的值
xn.ChildNodes;//这个结点的所有子结点
xn.ParentNode;//这个结点的父结点

Read all data

When using it, first declare an XmlDocument object, and then call the Load method to load the XML file from the specified path.

BookModel is a book model

#region XmlDocument读取

public static void XmlDocumentReadDemo()
{
  //list
  List<BookModel> bookModeList = new List<BookModel>();

  //使用的时候,首先声明一个XmlDocument对象,然后调用Load方法,从指定的路径加载XML文件.
  XmlDocument doc = new XmlDocument();

  XmlReaderSettings settings = new XmlReaderSettings();
  settings.IgnoreComments = true;//忽略文档里面的注释
  using (XmlReader reader = XmlReader.Create(@"d:/demo.xml", settings))
  {
    doc.Load(reader);
    //doc.Load(@"d:/demo.xml");
    //然后可以通过调用SelectSingleNode得到指定的结点,通过GetAttribute得到具体的属性值.参看下面的代码
    // 得到根节点bookstore
    XmlNode xn = doc.SelectSingleNode("bookstore");
    // 得到根节点的所有子节点
    XmlNodeList xnl = xn.ChildNodes;

    foreach (XmlNode xn1 in xnl)
    {
      BookModel bookModel = new BookModel();
      // 将节点转换为元素,便于得到节点的属性值
      XmlElement xe = (XmlElement)xn1;
      // 得到Type和ISBN两个属性的属性值
      bookModel.BookISBN = xe.GetAttribute("ISBN").ToString();
      bookModel.BookType = xe.GetAttribute("Type").ToString();
      // 得到Book节点的所有子节点
      XmlNodeList xnl0 = xe.ChildNodes;
      bookModel.BookName = xnl0.Item(0).InnerText;
      bookModel.BookAuthor = xnl0.Item(1).InnerText;
      bookModel.BookPrice = Convert.ToDouble(xnl0.Item(2).InnerText);

      bookModeList.Add(bookModel);
    }
  }
  bookModeList.Add(new BookModel());
}

#endregion XmlDocument读取

The running results are as follows:

Use XmlTextReader to read

When using XmlTextReader to read data, first create a stream, and then use the read() method to continuously read downwards, and perform corresponding operations according to the type of node read. As follows:

#region XmlTextReaderDemo

public static void XmlTextReaderDemo()
{
  XmlTextReader reader = new XmlTextReader(@"d:/demo.xml");
  List<BookModel> modelList = new List<BookModel>();
  BookModel model = new BookModel();
  while (reader.Read())
  {
    if (reader.NodeType == XmlNodeType.Element)
    {
      if (reader.Name == "book")
      {
        model.BookType = reader.GetAttribute("Type");
        model.BookISBN = reader.GetAttribute("ISBN");
      }
      if (reader.Name == "title")
      {
        model.BookName = reader.ReadElementContentAsString();
      }
      if (reader.Name == "author")
      {
        model.BookAuthor = reader.ReadElementString().Trim();
      }
      if (reader.Name == "price")
      {
        model.BookPrice = Convert.ToDouble(reader.ReadElementString().Trim());
      }
      //for(int i=0;i<reader.AttributeCount;i++)
      //{
      //  reader.MoveToAttribute(i);
      //}
    }

    if (reader.NodeType == XmlNodeType.EndElement)
    {
      modelList.Add(model);
      model = new BookModel();
    }
  }
  reader.Close();
  modelList.Add(new BookModel());
}

#endregion XmlTextReaderDemo

Using Linq to Xml to read

Linq is a new feature that appeared in C# 3.0 , using it can easily operate many data sources, including XML files. Using Linq to operate XML files is very convenient and relatively simple.

Must reference using System.Linq;using System.Xml.Linq;

##

#region 读取所有的数据

XElement xe = XElement.Load(@"d:/demoLinq.xml");
//xe.Descendants
var elements = from ele in xe.Elements()
        select ele;
List<BookModel> modelList = new List<BookModel>();
foreach (var ele in elements)
{
  BookModel model = new BookModel();
  model.BookAuthor = ele.Element("author").Value;
  model.BookName = ele.Element("title").Value;
  model.BookPrice = Convert.ToDouble(ele.Element("price").Value);
  model.BookISBN = ele.Attribute("ISBN").Value;
  model.BookType = ele.Attribute("Type").Value;

  modelList.Add(model);
}
modelList.Add(new BookModel());

#endregion 读取所有的数据

Summary

1.The advantage of the XmlDocument method is that it is easy to find

2.The XmlTextReader method is a stream-reading method that uses less memory temporarily

3.Linq to The latest method of Xml is also the recommended method. The code is small and easy to understand.

The above is the detailed code explanation of the three implementation methods of C# reading XML. For more related content, please pay attention to the PHP Chinese website (www.php.cn) !


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn