Write To XML File

image_pdfimage_print
   

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;


namespace Client.Chapter_22___XML
{
  public class WriteToXMLFile
  {
    static void Main(string[] args)
    {
      string document = "newbooks.xml";
      XmlTextWriter myXmlTextWriter = null;
      XmlTextReader myXmlTextReader = null;

      myXmlTextWriter = new XmlTextWriter(args[1], null);
      myXmlTextWriter.Formatting = Formatting.Indented;
      myXmlTextWriter.WriteStartDocument(false);
      myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd", null);
      myXmlTextWriter.WriteComment("This file represents another fragment of a book store inventory database");
      myXmlTextWriter.WriteStartElement("bookstore");
      myXmlTextWriter.WriteStartElement("book", null);
      myXmlTextWriter.WriteAttributeString("genre", "autobiography");
      myXmlTextWriter.WriteAttributeString("publicationdate", "1979");
      myXmlTextWriter.WriteAttributeString("ISBN", "0-7356-0562-9");
      myXmlTextWriter.WriteElementString("title", null, "The Autobiography of Mark Twain");
      myXmlTextWriter.WriteStartElement("Author", null);
      myXmlTextWriter.WriteElementString("first-name", "Mark");
      myXmlTextWriter.WriteElementString("last-name", "Twain");
      myXmlTextWriter.WriteEndElement();
      myXmlTextWriter.WriteElementString("price", "7.99");
      myXmlTextWriter.WriteEndElement();
      myXmlTextWriter.WriteEndElement();

      //Write the XML to file and close the writer
      myXmlTextWriter.Flush();
      myXmlTextWriter.Close();
      if (myXmlTextWriter != null)
        myXmlTextWriter.Close();
    }
  }

}

           
          


Writing XML with the XmlWriter Class

image_pdfimage_print


   


using System;
using System.IO;
using System.Xml;
   
class MainClass
{
    static public void Main()
    {
        XmlTextWriter XmlWriter = new XmlTextWriter(Console.Out);
        
        XmlWriter.WriteStartDocument();
        XmlWriter.WriteComment("This is the comments.");
        XmlWriter.WriteStartElement("BOOK");
        XmlWriter.WriteElementString("TITLE", "this is the title.");
        XmlWriter.WriteElementString("AUTHOR", "I am the author.");
        XmlWriter.WriteElementString("PUBLISHER", "who is the publisher");
        XmlWriter.WriteEndElement();
        XmlWriter.WriteEndDocument();
    }
}
           
          


Read and Write XML Without Loading an Entire Document into Memory

image_pdfimage_print

using System;
using System.Xml;
using System.IO;
using System.Text;

public class ReadWriteXml {
private static void Main() {
FileStream fs = new FileStream(“products.xml”, FileMode.Create);
XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);

w.WriteStartDocument();
w.WriteStartElement(“products”);

w.WriteStartElement(“product”);
w.WriteAttributeString(“id”, “01”);
w.WriteElementString(“name”, “C#”);
w.WriteElementString(“price”, “0.99”);
w.WriteEndElement();

w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

Console.WriteLine(“Document created.”);

fs = new FileStream(“products.xml”, FileMode.Open);
XmlTextReader r = new XmlTextReader(fs);

while (r.Read()) {
if (r.NodeType == XmlNodeType.Element) {
Console.WriteLine(“<" + r.Name + ">“);
if (r.HasAttributes) {
for (int i = 0; i < r.AttributeCount; i++) { Console.WriteLine(" ATTRIBUTE: " + r.GetAttribute(i)); } } }else if (r.NodeType == XmlNodeType.Text) { Console.WriteLine(" VALUE: " + r.Value); } } } } [/csharp]

Create XML document with XmlWriter

image_pdfimage_print
   


using System;
using System.Xml;
using System.IO;
using System.Text;

class MainClass {
    private static void Main() {
        FileStream fs = new FileStream("products.xml", FileMode.Create);

        XmlWriter w = XmlWriter.Create(fs);

        w.WriteStartDocument();
        w.WriteStartElement("products");

        w.WriteStartElement ("product");
        w.WriteAttributeString("id", "1001");
        w.WriteElementString("productName", "Gourmet Coffee");
        w.WriteElementString("productPrice", "0.99");
        w.WriteEndElement();

        w.WriteStartElement("product");
        w.WriteAttributeString("id", "1002");
        w.WriteElementString("productName", "Tea Pot");
        w.WriteElementString("productPrice", "12.99");
        w.WriteEndElement();

        w.WriteEndElement();
        w.WriteEndDocument();
        w.Flush();
        fs.Close();

    }
}

           
          


Pretty Print XML

image_pdfimage_print
   
 
#region License and Copyright
/*
 * Dotnet Commons Xml
 *
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 
 * for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this library; if not, write to the 
 * Free Software Foundation, Inc., 
 * 59 Temple Place, 
 * Suite 330, 
 * Boston, 
 * MA 02111-1307 
 * USA 
 * 
 */
#endregion

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Serialization;

//using Dotnet.Commons.Reflection;

namespace Dotnet.Commons.Xml
{
  
  ///  
  /// <summary>
  /// This utility class contains wrapper functions that help to ease the handling and 
    /// manipulation of Xml documents, such as adding an element, adding an attribute
    /// to an element, copying and cloning of nodes, etc.
  ///
  /// </summary>
  /// 
    
  public abstract class XmlUtils
  {
    /// -----------------------------------------------------------
    /// <summary>
    /// Pretty Print XML
    /// </summary>
    /// <param name="xml"></param>
    /// <returns>Pretty print xml string</returns>
    /// <remarks> Thanks to http://dotnet.editme.com/codePrettyPrintXML</remarks>
    /// -----------------------------------------------------------
    public static string PrettyPrint(string xml)
    {
      XmlDocument xmlDom   = new XmlDocument();

      // Load the XmlDocument with the XML.
      xmlDom.LoadXml(xml);

      return PrettyPrint(xmlDom);
    }


    /// -----------------------------------------------------------
    /// <summary>
        /// Print Print an <see cref="XmlDocument"/>
    /// </summary>
    /// <param name="xmlDom"></param>
    /// <returns></returns>
    /// -----------------------------------------------------------
    public static string PrettyPrint(XmlDocument xmlDom)
    {
            return PrettyPrint(xmlDom, true);
    }


        /// <summary>
        /// Print Print an <see cref="XmlNode"/>
        /// </summary>
        /// <param name="xmlNode"></param>
        /// <returns></returns>
        public static string PrettyPrint(XmlNode xmlNode)
        {
            return PrettyPrint(xmlNode, false);
        }


        /// <summary>
        /// Pretty Print an <see cref="XmlDocument"/> or an <see cref="XmlNode"/>
        /// </summary>
        /// <param name="xmlObj"></param>
        /// <param name="isXmlDoc"></param>
        /// <returns></returns>
        public static string PrettyPrint(object xmlObj, bool isXmlDoc)
        {

            if (!(xmlObj is XmlDocument || xmlObj is XmlDataDocument ||
                xmlObj is XmlNode || xmlObj is XmlElement))
                throw new ArgumentException("xmlObj must be either an XmlDocument, XmlDataDocument, XmlNode or an XmlElement object");

            String prettyXml = "";

            MemoryStream memStream = new MemoryStream();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memStream, Encoding.Unicode);

            try
            {
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlTextWriter.Indentation = 4;
                xmlTextWriter.QuoteChar = &#039;&#039;&#039;;


                // Write the XML into a formatting XmlTextWriter
                if (xmlObj is XmlDocument)
                    ((XmlDocument)xmlObj).WriteContentTo(xmlTextWriter);
                else if (xmlObj is XmlDataDocument)
                    ((XmlDataDocument)xmlObj).WriteContentTo(xmlTextWriter);
                else
                    ((XmlNode)xmlObj).ParentNode.WriteContentTo(xmlTextWriter);

                
                xmlTextWriter.Flush();
                memStream.Flush();

                // Have to rewind the MemoryStream in order to read
                // its contents.
                memStream.Position = 0;

                // Read MemoryStream contents into a StreamReader.
                StreamReader streamReader = new StreamReader(memStream);

                // Extract the text from the StreamReader.
                String sFormattedXML = streamReader.ReadToEnd();

                prettyXml = sFormattedXML;
            }
            catch
            {
            }

            memStream.Close();
            xmlTextWriter.Close();

            return prettyXml;
        }
    }
}

   
     


Display XML file content to TreeView

image_pdfimage_print


   
 

using System;
using System.Windows.Forms;
using System.Xml;

public class XmlTreeDisplay : System.Windows.Forms.Form{
    private System.Windows.Forms.TreeView treeXml = new TreeView();

    public XmlTreeDisplay() {
        treeXml.Nodes.Clear();
        this.Controls.Add(treeXml);
        // Load the XML Document
        XmlDocument doc = new XmlDocument();
        try {
            doc.Load("books.xml");
        }catch (Exception err) {

            MessageBox.Show(err.Message);
            return;
        }

        ConvertXmlNodeToTreeNode(doc, treeXml.Nodes);
        treeXml.Nodes[0].ExpandAll();
    }

    private void ConvertXmlNodeToTreeNode(XmlNode xmlNode, 
      TreeNodeCollection treeNodes) {

        TreeNode newTreeNode = treeNodes.Add(xmlNode.Name);

        switch (xmlNode.NodeType) {
            case XmlNodeType.ProcessingInstruction:
            case XmlNodeType.XmlDeclaration:
                newTreeNode.Text = "<?" + xmlNode.Name + " " + 
                  xmlNode.Value + "?>";
                break;
            case XmlNodeType.Element:
                newTreeNode.Text = "<" + xmlNode.Name + ">";
                break;
            case XmlNodeType.Attribute:
                newTreeNode.Text = "ATTRIBUTE: " + xmlNode.Name;
                break;
            case XmlNodeType.Text:
            case XmlNodeType.CDATA:
                newTreeNode.Text = xmlNode.Value;
                break;
            case XmlNodeType.Comment:
                newTreeNode.Text = "<!--" + xmlNode.Value + "-->";
                break;
        }

        if (xmlNode.Attributes != null) {
            foreach (XmlAttribute attribute in xmlNode.Attributes) {
                ConvertXmlNodeToTreeNode(attribute, newTreeNode.Nodes);
            }
        }
        foreach (XmlNode childNode in xmlNode.ChildNodes) {
            ConvertXmlNodeToTreeNode(childNode, newTreeNode.Nodes);
        }
    }
    public static void Main(){
       Application.Run(new XmlTreeDisplay());
    }
}
/*
<books>
  <A property="a">
    <B>text</B>
    <C>textg</C>
    <D>99999</D>
  </A>
</books>
*/

           
         
     


XML transformation: transform XML file to HTML file

image_pdfimage_print
   

using System;
using System.Xml;           
using System.Xml.Xsl;       
using System.Xml.XPath;     
using System.IO;            

  public class XSLDemo
  {
    [STAThread]
    static void Main(string[] args)
    {
      XslTransform xslt = new XslTransform();
      xslt.Load("XSLTemplate.xsl");
      XPathDocument xDoc = new XPathDocument("Books.xml");
      XmlTextWriter writer = new XmlTextWriter("Books.html", null);
      xslt.Transform(xDoc, null, writer, new XmlUrlResolver());
      writer.Close();
      StreamReader stream = new StreamReader("Books.html");
      Console.Write(stream.ReadToEnd());
    }
  }
/*
<books>
  <book category="A">
    <title>title</title>
    <author>Tom</author>
    <price>19.95</price>
  </book>
  <book category="B">
    <title>title 2</title>
    <author>Jack</author>
    <price>9.95</price>
  </book>
</books>
*/

/*
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "/" >

<html>
<head><title>A list of books</title></head>
<style>
.headerClass { background-color=#ffeedd; }
</style>
<body>
<B>List of books</B>
<table border="1">
<tr>
  <td class="headerClass">Title</td>
  <td class="headerClass">Author</td>
  <td class="headerClass">Price</td>
</tr>
<xsl:for-each select="//books/book">
<tr>
  <td><xsl:value-of select="title"/></td>
  <td><xsl:value-of select="author"/></td>
  <td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>

</xsl:template>
</xsl:stylesheet>

*/