用C#讀取XML指定節點下的值

來源:互聯網
上載者:User
-------------------XML code<Employees>  <Employee name="李宇秋" age="23">    <Address>       長江路178號    </Address>    <Department>       演唱部    </Department>  </Employee>  <Employee name="曾不可" age="24">    <Address>       火星路239號   </Address>    <Department>       舞蹈部   </Department>  </Employee>  <Employee name="張學敵" age="27">    <Address>       香港街13號   </Address>    <Department>       偶像部   </Department>  </Employee></Employees>--------------比如:要擷取 name="曾不可" 的節點下面的 Address 節點的值“火星路239號”,C#如何??

OK,在linq之前,可以試用XMLDocment將xml整個檔案讀進來,然後比如可以用xpath再進行分析。
自從有了linq,一切都變得簡單了,實現代碼如下:

//假設以上xml我們儲存在一個本地xml檔案 D:\Microsoft Work\XMLPath\sampleXML.xml 中public List<string> GetXMLResult(){       XElement xelement = XElement.Parse(@"D:\Microsoft Work\XMLPath\sampleXML.xml");       var query = xelement.Descendants("Employee").Where(x => x.Attribute("name").Value == "曾不可").Select(x => x.Element("Address").Value);       if (query != null && query.Count() > 0)             return query.ToList<string>();       return null;}

 

這樣即可。

 

OK,我們現在將上面的XML結構稍作改動一下,

-------------------XML code<Employees>  <Employee name="李宇秋" age="23">    <Address>       <Province>          長江省       </Province>       <Road>          長江路178號     </Road>   </Address>    <Department>       演唱部    </Department>  </Employee>  <Employee name="曾不可" age="24">     <Address>       <Province>          火星省     </Province>       <Road>          火星路239號     </Road>    <Address>    <Department>       舞蹈部   </Department>  </Employee>  <Employee name="張學敵" age="27">    <Address>       <Province>          香港省     </Province>       <Road>          香港街239號     </Road>    <Address>    <Department>       偶像部   </Department>  </Employee></Employees>--------------現在:仍然是要擷取 name="曾不可" 的節點下面的 Address 節點下Road結點的值“火星路239號”,
--------------C#如何??

 

OK,這時候linq的優勢就很明顯了,實現代碼如下:

private List<string> GetXMLResult(string xmlPath, string employeeName){     XElement xelement = XElement.Load(xmlPath);     var query = xelement.Descendants("Employee").SingleOrDefault(x => x.Attribute("name").Value == employeeName);     if (query != null && query.Count() > 0)     {         var queryResult = query.Descendants("Road").Select(m => m.Value);         if (queryResult.Count() > 0)            return queryResult.ToList<string>();     }     return null;}

如果沒有Linq To XML,用xpath也可以解決這樣的取值問題,但是會變得複雜很多。

聯繫我們

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