<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Fremus.co.za &#187; DataSets to XML</title>
	<atom:link href="http://www.fremus.co.za/blog/tag/datasets-to-xml/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fremus.co.za/blog</link>
	<description>Demistifying Life and Web Development</description>
	<lastBuildDate>Sun, 27 Nov 2011 15:56:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Linq to XML and DataSet to XML</title>
		<link>http://www.fremus.co.za/blog/2009/10/linq-to-xml-and-dataset-to-xml/</link>
		<comments>http://www.fremus.co.za/blog/2009/10/linq-to-xml-and-dataset-to-xml/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 13:29:00 +0000</pubDate>
		<dc:creator>fr3dr1k</dc:creator>
				<category><![CDATA[Application Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DataSets to XML]]></category>
		<category><![CDATA[LINQ to XML]]></category>

		<guid isPermaLink="false">http://www.fremus.co.za/blog/?p=483</guid>
		<description><![CDATA[On Monday I started working through some LINQ to XML and it got me so excited that I misunderstood some project requirements that ended up being quite wrong. It did not, however, diminish my enthusiasm. I ended up using a small part of the code in the end anyway, even though it was not in [...]]]></description>
			<content:encoded><![CDATA[<p>On Monday I started working through some LINQ to XML and it got me so excited that I misunderstood some project requirements that ended up being quite wrong. It did not, however, diminish my enthusiasm. I ended up using a small part of the code in the end anyway, even though it was not in a production environment. </p>
<p>Lets say you have a collection of XML documents and you would like to know what elements appear in all of them, so at the end of it all you have a single of list of elements that appear between all of them. This is how I did it:</p>
<pre name="code" class="csharp">
            DirectoryInfo di = new DirectoryInfo(ConfigurationManager.AppSettings["XMLDirectory"].ToString());
            Dictionary<string, string> values = new Dictionary<string, string>();
            FileInfo[] fi = di.GetFiles();
            Response.Write("
<table>");
            Response.Write("
<tr>");
            foreach (FileInfo file in fi)
            {
                //Response.Write(@"
<td valign=""top"">");
                //Response.Write("<strong>" + file.Name + "</strong><br/>");
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreWhitespace = true;
                settings.IgnoreComments = true;
                settings.ConformanceLevel = ConformanceLevel.Fragment;
                //Console.WriteLine(file.Name);
                XmlReader reader = XmlReader.Create(file.Directory + @"\" + file.Name, settings);
                XDocument document = XDocument.Load(reader);
                IEnumerable<XElement> elems = from items in document.Descendants("Bond")
                                              select items;

                foreach (XElement elem in elems)
                {
                    IEnumerable<XElement> childElems = from items in elem.Descendants()
                                                       select items;
                    foreach (XElement xelem in childElems)
                    {
                        //Response.Write(xelem.Name.ToString() + " " + xelem.Parent.Name.ToString() + "<br >");
                        if (!values.ContainsKey(xelem.Name.ToString()))
                        {
                            values.Add(xelem.Name.ToString(), xelem.Parent.Name.ToString());
                        }
                    }
                }
                //Response.Write("</td>

");
            }
            Response.Write("</tr>

");
            Response.Write("
<tr>");
            Response.Write(@"
<td valign=""top"">");
            Response.Write("<strong>Combined</strong>");

            var combined = values
                .OrderBy(kv => kv.Value);

            foreach (KeyValuePair<string, string> kvp in combined)
            {
                Response.Write(kvp.Key + " " + kvp.Value + "");
            }
            Response.Write("</td>

");
            Response.Write("</tr>

");
            Response.Write("</table>

");
</pre>
<p>I use the DirectoryInfo class on a directory, XMLPath in this instance. I then declare an array of type FileInfo, which I then use in a foreach (Enumerate) loop using the FileInfo class. I then use the XMLReader class to read the XML document that is represented through the FileInfo class to read the XML. Inside the foreach loop I create an enumerable instance of XElement  called elems which uses LINQ to XML to select all the items. I then create a second enumerable instance of XElements called childElems. I then iterate (enumerate) through the childElems instance and add the Name of the element as the key and the parent as a value to a dictionary of type string,string which I declared earlier. This will loop through all files in the directory and generate a dictionary with combined values. Once its in a dictionary you can simply enumerate through it. I ordered it first by using the OrderBy extension method. Once it has been ordered I enumerate through it with a KeyValuePair and display the combined list. This approach has apparent weaknesses in that it uses the name of a node as a key and the parent as the value. What if two nodes are equal but have different parents? It served a purpose for me though.</p>
<p>The second piece of code I would like to show is an example of converting a dataset to xml and returning the raw XML. Let&#8217;s say you have an arbitrary function and you want to return the raw XML of a dataset, you could use:</p>
<pre name="code" class="csharp">
            StringWriter writer = new StringWriter();
            transactionDS.WriteXml(writer);
            xmlizedString = writer.ToString();

            return xmlizedString;
</pre>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save" onclick="urchinTracker('/outgoing/www.addtoany.com/share_save?referer=');"><img src="http://www.fremus.co.za/blog/wp-content/plugins/add-to-any/favicon.png" width="16" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.fremus.co.za/blog/2009/10/linq-to-xml-and-dataset-to-xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

