用XML代码扩展c#代码



我从链接"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>

我不确定我是否理解对了,那

呢?
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());
}
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();

相关内容

  • 没有找到相关文章

最新更新