查找和过滤XML数据

时间:2013-05-13 19:27:21

标签: c# xml syntax linq-to-xml

我这里有一个XML文档:

<?xml version="1.0" encoding="utf-8" ?>
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
    <TITLE>Test Title 1</TITLE>
    <ARTIST>Test Name 1</ARTIST>
    <COUNTRY>Test Country 1</COUNTRY>
    <COMPANY>Test Company 1</COMPANY>
    <PRICE>100.00</PRICE>
    <YEAR>1985</YEAR>
  </CD>
  <CD>
    <TITLE>Test Title 3</TITLE>
    <ARTIST>Test Name 3</ARTIST>
    <COUNTRY>Test Country 3</COUNTRY>
    <COMPANY>Test Company 3</COMPANY>
    <PRICE>1.99</PRICE>
    <YEAR>1984</YEAR>
  </CD>
  <CD>
    <TITLE>Test Title 2</TITLE>
    <ARTIST>Test Name 2</ARTIST>
    <COUNTRY>Test Country 2</COUNTRY>
    <COMPANY>Test Company 2</COMPANY>
    <PRICE>19.99</PRICE>
    <YEAR>1985</YEAR>
  </CD>
</CATALOG>

我要做的是找到1985年的所有CD。我对LINQ to XML很新,我不知道我在做什么。因为大多数互联网资源都是非常具体的例子,我在将它应用到我的例子时遇到了麻烦。

这是我到目前为止编写的C#:

namespace ReadingXML
{
    class Program
    {
        static void Main(string[] args)
        {
            XElement xelement = XElement.Load("..\\..\\music.xml");
            IEnumerable<XElement> music = xelement.Elements();
            /*// Read the entire XML
            foreach (var item in catalogues)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();*/

            var query = from item in music.Descendants("CD")
                        select new { year = item.Element("YEAR").Equals(1985) };

            foreach (var item in query)
                Console.WriteLine(item.ToString());

            Console.ReadLine();
        }
    }
}

有人可以告诉我如何实现我想要做的事情和/或为什么我的代码无法运作?

2 个答案:

答案 0 :(得分:3)

XDocument X = XDocument.Load(@"XMLFileLocation");
var CDsIn1985 = X.Element("CATALOG").Elements("CD").Where(E => E.Element("YEAR").Value == "1985");

foreach (var item in CDsIn1985)
{
     Console.WriteLine(String.Format("Title : {0}, Artist : {1}", item.Element("TITLE").Value, item.Element("ARTIST").Value));
}

答案 1 :(得分:0)

另一种方法是使用字符串插值

foreach (var item in CDsIn1985)
  {
    Console.WriteLine(String.Format($"Title : {item.Element("TITLE").Value}, Artist : { item.Element("ARTIST").Value}"));
  }