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:

<vehicles>
<cars>
<car>
<brand>
Toyota
</brand>
</car>
</cars>
<trucks>
<truck>
<brand>
Ford
</brand>
</truck>
</trucks>
</vehicles>

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

Please advise.
GY1680Asked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi GY168;

This should do what you need.

Fernando
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];

Open in new window

0
 
chinawalCommented:
Try this

select h.salesheaderid, h.ship_customer, h.DeliveryDate, x.oldvalue,x.newvalue,x.updatedate
from tblSalesHeader h
      left join
            (select top 1 a.*
             from Audit a
             inner join tblSalesHeader h
             on a.RecordKey = h.SalesHeaderID
             order by a.updatedate desc) x
 on x.recordkey = h.salesheaderid

0
 
chinawalCommented:
sorry.. too many windows open.. wrong answer to wrong question..
0
 
GY1680Author Commented:
Worked perfectly.  Thank you very much for your help.
0
 
Fernando SotoRetiredCommented:
Not a problem, glad I was able to help.  ;=)
0
All Courses

From novice to tech pro — start learning today.