繁体   English   中英

使用LinQ读取XML文件

[英]Read XML file using LinQ

这是我的XML文件。

<?xml version="1.0" encoding="utf-8"?>
<locstrings>  
 <section name="section1">
    <locstring ID="sectionID1">
        <Name>SectionName1</Name>
    </locstring>
 </section>  
 <section name="section2">
     <locstring ID="sectionID2">
        <Name>SectionName2</Name>
     </locstring>
    <locstring ID="SectionID3">
         <Name>SectionName3</Name>
     </locstring>
 </section>

</locstrings>
  1. 我想读取此xml元素,并使用C#中的Linq将(仅节名称)绑定到datagrid1中。
  2. 基于DataGrid1行选择,我想使用linQ在dataGrid2中显示sectionID和sectionName。

这是一些示例LINQ to XML,用于从示例XML文件获取数据:

        XDocument xml = XDocument.Load(@"<path to your xml file"); 

        var resultSet = from x in xml.Descendants("section")                          
                        select x.Attribute("name");

        var resultsSet2 = from x in xml.Descendants("section")
                          where x.Attribute("name") == "<the selected value of your data grid>"
                          select new
                          {                               
                              id = x.Element("locstring").Attribute("ID").Value,
                              name = x.Element("locstring").Element("Name").Value
                          };

您将需要设置数据网格,然后使用.DataSource属性绑定结果集,然后在数据网格上调用.DataBind()方法。

您还需要在第一个DataGrid上设置SelectedIndexChanged事件处理程序,以捕获选定的值,并使用LINQ to XML代码作为resultSet2来获取第二个网格结果集。

DataGrid绑定和选择已得到很好的记录。 但是这里有一些有关如何执行此操作的MSDN文档:

数据绑定到DataGrid控件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM