Linq 解決 XML讀寫執行個體

來源:互聯網
上載者:User

Linq To XML的核心類XElement,一個XElement表示一個節點,new XElement("Order"),建立一個名字為Order的標籤,調用Add增加子節點,也是XElement 對象!

下面是幾種LINQ操作XML的常見形式。

///寫檔案(產生節點性質的)

 代碼如下 複製代碼

XElement ePersons = new XElement("Persons"); 

XElement ptom = new XElement("Person"); //增加一個Person節點 

ptom.Add(new XElement("Name", "Tom"));//在ptom下再增加子節點 

ptom.Add(new XElement("Age", "18")); 

ePersons.Add(ptom);

XElement pjack = new XElement("Person");
pjack.Add(new XElement("Name", "Jack"));
pjack.Add(new XElement("Age", "20"));
ePersons.Add(pjack);

最終產生:

 代碼如下 複製代碼
<?xml version="1.0" encoding="utf-8" ?>
<Persons>
  <Person>
    <Name>Tom</Name>
    <Age>18</Age>
  </Person>
  <Person>
    <Name>Jack</Name>
    <Age>20</Age>
  </Person>
</Persons>

 


///寫檔案(產生屬性性質的)

 XElement ptom = new XElement("Person");  

 代碼如下 複製代碼

ptom.Add(new XAttribute("Name", "tom"));//添加XAttribute就產生屬性  

ptom.Add(new XAttribute("Age", "18"));  

ePersons.Add(ptom);    

XElement pjack = new XElement("Person");  

pjack.Add(new XAttribute("Name", "jack"));  

pjack.Add(new XAttribute("Age", "20"));  

ePersons.Add(pjack);

最終產生:

 代碼如下 複製代碼

<Persons>
  <Person Name="tom" Age="18"/>
  <Person Name="jack" Age="20"/>
</Persons>

//讀XML 讀取節點格式的值

 代碼如下 複製代碼

 XDocument xd= XDocument.Load("XML檔案地址");         

foreach (XElement item in xd.Root.Descendants("Person"))//得到每一個Person節點,得到這個節點再取他的Name的這個節點的值          

  {               Console.WriteLine(item.Element("Age").Value);//Person的節點的下得節點為Name的            }   

注釋:doc.root(得到根節點的XElement對象).XElement(“tagname”)方法得到的就是節點下第一個名字為tagname的節點。  如果doc.root。XElements(複數形式)就是得到所有的子節點,Descendants("“tagname”")子孫節點 

 

 

//讀XML 讀取屬性格式的值

 代碼如下 複製代碼

 XDocument xd= XDocument.Load(@"D:Program FilesDemoDemoConsoleApplication2XMLFile2.xml");             foreach (XElement item in xd.Root.Descendants("Person"))//得到每一個Person節點,得到這個節點再取他的Name的這個節點的值            

{       

Console.WriteLine(item.Attribute("Age").Value);//Person的節點的下得節點為Name的             } 

聯繫我們

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