从XML文件中检索特定数据 [英] Retrieve Specific Data from XML file

查看:53
本文介绍了从XML文件中检索特定数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于链接http://www.codeproject.com/Tips/146237/Reading-XML-documents-using-LINQ中的代码。如果我需要检索< Subject1>的数据和< Subject2>,新c#应如何替换此代码listBox1.Items.Add(b.Element(Subject)。Value.Trim());



谢谢!





Based on the code from the link "http://www.codeproject.com/Tips/146237/Reading-XML-documents-using-LINQ". If I need to retrieve the data of <Subject1> and <Subject2>, how should the new c# be by replacing this code "listBox1.Items.Add(b.Element("Subject").Value.Trim());"

Thanks!


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







<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>

推荐答案

它应该是这样的:



It should be something like this:

XDocument xdoc = XDocument.Load("fullfilepath.xml");

var qry  = xdoc.Root
		.Descendants("Subject")
		.Select(n=> new 
			{
				sub1 = n.Element("Subject1").Value,
				sub2 = n.Element("Subject2").Value
			}).ToList();



ListBox1.DataSource = qry;



结果:


ListBox1.DataSource = qry;

Result:

sub1      sub2
Subject1a Subject1a 
Subject2b Subject2b





如需了解更多信息,请参阅:

XDocument.Load方法(字符串) [ ^ ]

如何:绑定Windows窗体组合框或ListBox控制数据 [ ^ ]


这篇关于从XML文件中检索特定数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆