使用XML代码扩展C#代码

时间:2015-06-07 14:44:30

标签: c# xml linq

我从链接“http://www.codeproject.com/Tips/146237/Reading-XML-documents-using-LINQ”获得了一些启发。

如果我需要检索Subject1Subject2的数据,那么新的c#应该如何替换此代码listBox1.Items.Add(b.Element("Subject").Value.Trim());

C#:

var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book") select nodes;

if (books != null)
{
    foreach (var b in books)
    {
        listBox1.Items.Add(b.Element("Subject").Value.Trim());

    }
}

XML:

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book>
    <Subject>
    <Subject1>Subject1a</Subject1>
    <Subject2>Subject1a</Subject2>
    </Subject>
    <Content>
      History,Geography
    </Content>
  </Book>

  <Book>
    <Subject>
    <Subject1>Subject2b</Subject1>
    <Subject2>Subject2b</Subject2>
    </Subject>
    <Content>
      Biology,Chemistry,Physics
    </Content>
  </Book>
</Books>

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解正确,

foreach (var b in books) {
    var s = b.Element("Subject");
    listBox1.Items.Add(s.Element("Subject1").Value.Trim());
    listBox1.Items.Add(s.Element("Subject1").Value.Trim());
}

答案 1 :(得分:0)

var items = (from node in System.Xml.Linq.XElement.Parse(xml).Elements("Book")
                     let subject = node.Element("Subject")
                     select new
                     {
                         Subject1 = subject.Element("Subject1"),
                         Subject2 = subject.Element("Subject2")

                     }).ToList();