简体   繁体   中英

Parsing an XML file with a filter

I am trying to figure out how to filter out stuff from an .xml file and take the stuff I want and put it into a DataGridView . I can get this working when I make a simple .xml file with <Names><Username>test</Username></Names> .

The problem I am having is sorting a more complex XML file. I have a form page and a button_click action then uses this to send the info to the DataGridView :

private void button1_Click(object sender, EventArgs e)
{           
    DataSet dsload = new DataSet();
    dsload.ReadXml("C:\\Users\\VSBox\\Desktop\\test1.xml");
    dgvParseProc.DataSource = dsload.Tables[0];
    //dgvParseProc.DataMember = "<ss:Row>";   //failed test filter          
}

This is a small portion of the XML file I am trying to filter out

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns="urn:schemas-microsoft-com:office:spreadsheet">
<ss:Styles>
<ss:Worksheet ss:Name="Sheet1">
<ss:Table>
<Column ss:autofitwidth="1"/>
<Column ss:autofitwidth="1"/>
<ss:Row ss:StyleID="1">
<ss:Cell ss:MergeAcross="2">
<ss:Data ss:Type="String"> ARK | Compare Intel® Products </ss:Data>
</ss:Cell>
</ss:Row>
    <ss:Row>
      <ss:Cell ss:StyleID="s22">
        <ss:Data ss:Type="String">Max Turbo Frequency</ss:Data>
      </ss:Cell>
      <ss:Cell ss:StyleID="s22">
        <ss:Data ss:Type="String">4.00 GHz</ss:Data>
      </ss:Cell>
    </ss:Row>

In the end I am trying to get the DataGridView to show 2 rows with the info.

||Max Turbo Frequency || 4.00||

Any info anyone can provide would be great.

the xml file seems to be quite complex, also including a different namespaces.

you can try the XPath parsing, this would parse all cells and insert as rows in a datagridview:

        var source = @"<?xml version='1.0' encoding='utf-8'?>
        <ss:Row>
          <ss:Cell ss:StyleID='s22'>
            <ss:Data ss:Type='String'>Max Turbo Frequency</ss:Data>
          </ss:Cell>
          <ss:Cell ss:StyleID='s22'>
            <ss:Data ss:Type='String'>4.00 GHz</ss:Data>
          </ss:Cell>
        </ss:Row>";;

        // load document without namespaces
        var doc = new XmlDocument();
        using (var r = new StringReader(source))
        using (var xReader = new XmlTextReader(r))
        {
            xReader.Namespaces = false;

            doc.Load(xReader);
        }
        // select all sub nodes, then all inner nodes, then take the text
        // create a list with anonymous objects containing the text value
        dataGridView1.DataSource =
            doc.SelectNodes("/*/*/*/text()").OfType<XmlNode>().Select(n => new { Value = n.Value }).ToList();

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