C#溫故而知新學習系列之XML編程—Xml讀取器XmlReader類(二)

來源:互聯網
上載者:User

  前言

    XmlReader類提供了對XML文檔內容快速的,只向前的訪問,但不適合對文檔內容和結構進行修改,XmlReader從XML文檔的頂部開始讀取資料,每次讀取一個節點

  閱讀目錄

  一:讀取XML文檔的步驟

    二:實現步驟

  三:運行效果

  一:讀取XML文檔的步驟

  1:使用XmlReader類的Create()方法建立該類的執行個體,並將XML文檔名稱作為參數傳入方法。

  2:建立一個迴圈調用Read()方法,逐節點讀取整個XML文檔,如果存在一個節點可被讀取則被返回true,當到達XML文檔最後時返回false。

  3:在這個迴圈當中,檢查XmlReader對象的屬性和方法,以獲得當前節點的資訊。

  執行個體 

   二:實現步驟

  1:XML檔案編寫

   <?xml version="1.0" encoding="utf-8" ?>
   <BookShops>
     <Book Number="product-001">
        <Name>西遊記</Name>
        <OthorName>大唐西遊傳</OthorName>
        <Author>吳承恩</Author>
        <Money>220</Money>
        <Details>
        東勝神州的傲來國花果山的一塊巨石孕育出了一隻明靈石猴,石猴後來拜須菩提為師後習得了七十二變,具有了通天本領,於是佔山為王,自稱齊天大聖。
        </Details>
     </Book>
     <Book Number="product-002">
        <Name>紅樓夢</Name>
        <OthorName>石頭記</OthorName>
        <Author>曹雪芹</Author>
        <Money>320</Money>
        <Details>
         女媧鍊石補天,所煉之石剩一塊未用,棄在大荒山無稽崖青埂峰下。此石“自經煆煉之後靈性已通”,因未被選中補天常悲傷自怨。一日,和尚茫茫大士、道士渺渺真人經過此地。
        </Details>
     </Book>
  </BookShops>

  2:代碼檔案編寫

  Form1.cs

  using System;

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

  namespace XmlReaderClass
  {
       public partial class Form1 : Form
       {
            public Form1()
            {
                InitializeComponent();
            }

             private void Form1_Load(object sender, EventArgs e)
             {
                 string strXmlPath = "XMLFile.xml";
                 XmlReader xml_reader = XmlReader.Create(strXmlPath);
                 while (xml_reader.Read())
                 {

           //擷取當前節點的類型,如果當前讀取的節點是文本類型就輸出文本資訊
           if (xml_reader.NodeType == XmlNodeType.Text)
                        {
                            this.label1.Text += xml_reader.Value + "\r\n";
                        }
                }
             }
       }
   }

  三:運行效果

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.