Linq to XML 讀取XML 備忘筆記

來源:互聯網
上載者:User
最近一個項目中有要用到 xml 讀取,我首先想到的是使用 Linq 讀取(XML 解析感覺有點麻煩),項目完成,現抽取其內容,作如下筆記備忘.

1. demo.xml

demo.xml

<?xml version="1.0" encoding="utf-8" ?>
<note>
  <conf>
    <to>infozero</to>
    <from>lerroy</from>
    <heading>測試資訊</heading>
    <body>第一條測試資訊</body>
    <title name="我的第一條訊息">from myself</title>
  </conf>
  <conf>
    <to>infozero@163.com</to>
    <from>text</from>
    <heading> 時刻提醒我 </heading>
    <body>這是一條測試資訊!</body>
    <title name="我的第二條訊息">from others</title>
  </conf>
</note>

2.在 程式中引用以下命名空間:

using System;
using System.Linq;
using System.Xml.Linq;

3.讀取方法如下:

main 函數入口

    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("demo.xml");
            var text = from t in doc.Descendants("conf")                    //定位到節點 
                       .Where(w => w.Element("to").Value.Contains('@'))   //若要篩選就用上這個語句 
                       select new
                       {
                           to = t.Element("to").Value,
                           froms = t.Element("from").Value,
                           head = t.Element("heading").Value,
                           body = t.Element("body").Value,
                           title = t.Element("title").Attribute("name").Value   //注意此處用到 attribute 
                       };
            foreach (var a in text)
            {
                Console.WriteLine(a.to);
                Console.WriteLine(a.froms);
                Console.WriteLine(a.head);
                Console.WriteLine(a.body);
                Console.WriteLine(a.title);
            }
            Console.ReadKey();
        }
    }

結果:

 

小結: Linq to Xml 確實是個好東西 ,它極大地方便了我們的編程。

---------- 後續補充:-----

另外一種 XML 格式 的解析參見:  http://www.cnblogs.com/portalsky/archive/2008/09/11/1289461.html 
XML 增刪改查: http://www.cnblogs.com/greatverve/archive/2010/07/13/linq-to-xml-one-begin.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.