簡體   English   中英

如何使用c#從xml文件中獲取特殊數據

[英]How to get special data from xml file using c#

大家好我有一個xml文件:

   <bookstore>
      <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
      </book>
      <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>30</price>
      </book>
      <book category="CHILDREN">
        <title lang="en">abc</title>
        <author>bcd</author>
        <year>2006</year>
        <price>29</price>
      </book>
      <book category="WEB">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
      </book>

</bookstore>

如何在category =“CHILDREN”時獲得價目表 我用的是C#。

示例:輸出為:哈利波特的價格為30,abc的價格為29

謝謝,

您可以使用LINQ to XML。 以下代碼將返回包含XML中所有數據的匿名類型實例的集合:

var xDoc = XDocument.Load("Input.txt");

var books = xDoc.Root
                .Elements("book")
                .Where(b => (string)b.Attribute("category") == "CHILDREN")
                .Select(b => new
                {
                    Title = (string)b.Element("title"),
                    Author = (string)b.Element("author"),
                    Year = (int)b.Element("year"),
                    Price = (decimal)b.Element("price")
                });

您可以在books上調用.First()方法,只獲得一個/第一個找到的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM