简体   繁体   中英

Read XML file using LinQ

This is my XML File.

<?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#.
  2. Based on DataGrid1 row selection, i want to display sectionID and sectionName in dataGrid2 using linQ.

Here is some sample LINQ to XML to get the data from the sample XML file:

        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.

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 binding and selection are very well documented. But here are some MSDN docs on how to do it:

Data Binding to a DataGrid Control

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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