Question : Load Partial XML Into Dataset

I'm trying to load xml from a file into a dataset, and I can do it using LINQ and XDocument.ReadXML(file) - but I'd like to only fill the dataset with a portion of the xml file's contents, rather than the entire file.  I'm wondering how best to give it a start tag or otherwise modify the dataset to only include the xml I want.

For example:





Toyota






Ford





In this example - I'd only like to populate my dataset with the Trucks values - and disregards the Cars values.

Please advise.

Answer : Load Partial XML Into Dataset

Hi GY168;

This should do what you need.

Fernando
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
using System.Xml;
using System.Xml.Linq;
using System.IO;


// Load XML document from disk
XDocument doc = XDocument.Load("XmlData.xml");
// The new document to hole the modified XML
XDocument outDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
// Linq query to get all the trucks elements
var results = from ele in doc.Descendants("trucks")
              select ele;
// Add the elements found in the result set.
foreach (XElement ele in results)
{
    outDoc.Add(ele);
}
// Create a byte array from the outDoc document
byte[] xmlBytes = new byte[outDoc.ToString().Length];
xmlBytes = Encoding.UTF8.GetBytes(outDoc.ToString());
// Read it into a memory stream to use with data set
MemoryStream ms = new MemoryStream(xmlBytes);
// Create the new data set
DataSet ds = new DataSet();
// Read the XML into the data set
ds.ReadXml(ms);
// Display the info in a data grid view
dataGridView1.DataSource = ds.Tables[0];
Random Solutions  
 
programming4us programming4us