简体   繁体   English

使用LinQ读取XML文件

[英]Read XML file using LinQ

This is my XML File. 这是我的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. I want to read this xml elements and bind(only Section name) into datagrid1 using Linq in C#. 我想读取此xml元素,并使用C#中的Linq将(仅节名称)绑定到datagrid1中。
  2. Based on DataGrid1 row selection, i want to display sectionID and sectionName in dataGrid2 using linQ. 基于DataGrid1行选择,我想使用linQ在dataGrid2中显示sectionID和sectionName。

Here is some sample LINQ to XML to get the data from the sample XML file: 这是一些示例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
                          };

You will need to setup your data grid and then bind the result sets using the .DataSource property, then call the .DataBind() method on the data grid. 您将需要设置数据网格,然后使用.DataSource属性绑定结果集,然后在数据网格上调用.DataBind()方法。

You will also need to set a SelectedIndexChanged event handler on your first DataGrid to capture the selected value and use the LINQ to XML code for the resultSet2 to get your second grids result set. 您还需要在第一个DataGrid上设置SelectedIndexChanged事件处理程序,以捕获选定的值,并使用LINQ to XML代码作为resultSet2来获取第二个网格结果集。

DataGrid binding and selection are very well documented. DataGrid绑定和选择已得到很好的记录。 But here are some MSDN docs on how to do it: 但是这里有一些有关如何执行此操作的MSDN文档:

Data Binding to a DataGrid Control 数据绑定到DataGrid控件

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

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