home
links
tips

code
users
tools
tutorials
projects
web
help
design

mudabone
suletzki
trans48
nutrition reality

MarthaAttire!

serialize XML


Many thanks to Karl @ http://www.meissnersd.com/csharp.htm for most of this code.

Attached are 3 classes - they're pasted below for reading purposes.


--------------- XMLBASE.CS  ---------------------

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;

namespace MSD.XmlLib { 

/// <summary>
///  This class encapsulated helper functions for 
///  moving the data from xml text to C#. 
///  
///  A natural way to use this class is to derived the xml root class from here
///  
///  Thanks to Karl @  http://www.meissnersd.com/csharp.htm
///  
/// </summary>
public class XmlBase { 


     /// <summary>
     ///  Read in filename, parse the xml and return the instansiated object in root
     /// </summary>
     /// <param name="filename"> the path of a file holding xml text.   The schme of the xml must match root Node type</param>
     /// <param name="rootNodeType">The System type of the root node class</param>
     static protected object DeserializeFile( string filename, System.Type rootNodeType ) { 
          FileStream  fs = new FileStream( filename, FileMode.Open, FileAccess.Read) ;

          if( fs == null ) 
               throw new FileNotFoundException( "XmlBase.DeserializeFile - Could not find file " + filename );

          return Deserialize( new XmlTextReader( fs ), rootNodeType );
     }

     /// <summary>
     ///  Parse the xml in xmlInstance and return the instansiated object in root
     /// </summary>
     /// <param name="str">xml structure contained in a raw string</param>
     /// <param name="rootNodeType">The System type of the root node class</param>
     static public object DeserializeString( string str, System.Type rootNodeType ) { 
          return Deserialize( new XmlTextReader( new StringReader( str ) ), rootNodeType );
     }

     /// <summary>
     ///  Read in the the xml in reader.  The schema of the xml must match the rootNodeType. 
     /// </summary>
     /// <param name="reader"></param>
     /// <param name="rootNodeType"></param>
     /// <returns></returns>
     static public object Deserialize( XmlReader reader, System.Type rootNodeType ) { 

          object root = null;
          try { 
               XmlSerializer serializer = new XmlSerializer( rootNodeType );
               root = serializer.Deserialize( reader );
          } catch( System.Exception ex ) {
               throw ex;               
          } finally { 
               reader.Close();
          }
          return root;
     } 


     virtual public string Serialize()
     {
          return Serialize(true);
     }
     virtual public string Serialize(bool RemoveEmptyTags) 
     { 
          //string xmlstr = null;   
          StringWriter sw = new StringWriter();
          XmlSerializer serializer = new XmlSerializer( this.GetType() );
          XmlTextWriter w =      new XmlTextWriter( sw );
          w.Formatting = Formatting.Indented;
          w.Indentation = 3;
          
          serializer.Serialize(w, this );
          w.Flush();
          w.Close();
          
          string str = sw.ToString();
          
          // Unicode attribute causes IE to choke on the XML files. 
          // so remove it so if they click on a file it will display nicely
          str = str.Replace( "encoding="utf-16"", "" ); 
          str = str.Replace("xsi:type="xsd:string"","");

          //str = str.Replace("&gt;",">").Replace("&lt;","<");
          
          if (RemoveEmptyTags == true)
          {
               string sXML = XMLRequests.utils.RemoveEmptyTags(str);
               return XMLRequests.utils.PrettyPrint(sXML);
          }
          else
          {
               return str;
          }
     }

     private void dp(object o)
     {
          System.Diagnostics.Debug.WriteLine(o.ToString());
     }


}


--------------- UTILS.CS    ---------------------

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.Xml.XPath;
using System.Xml.Xsl;


namespace XMLRequests
{
     public class utils
     {
          public utils()
          {
          }

          public static string RemoveEmptyTags(string sXML)
          {
               System.Text.StringBuilder sb = new StringBuilder();
               
               sb.Append("<?xml version="1.0" encoding="UTF-8"?>");
               sb.Append("<xsl:stylesheet ");
               sb.Append("     version="1.0" ");
               sb.Append("     xmlns:msxsl="urn:schemas-microsoft-com:xslt"");
               sb.Append("     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">");
               sb.Append("     <xsl:output method="xml" version="1.0" encoding="UTF-8"/>");
               sb.Append("   <!-- Whenever you match any node or any attribute -->");
               sb.Append("   <xsl:template match="node()|@*">");
               sb.Append("      <!-- Copy the current node -->");
               sb.Append("     <xsl:if test="normalize-space(.) != '' or normalize-space(./@*) != '' ">");
               sb.Append("          <xsl:copy>");
               sb.Append("              <!-- Including any attributes it has and any child nodes -->");
               sb.Append("               <xsl:apply-templates select="@*|node()"/>");
               sb.Append("          </xsl:copy>");
               sb.Append("     </xsl:if>");
               sb.Append("   </xsl:template>");
               sb.Append("</xsl:stylesheet>");
               return utils.transXMLStringThroughXSLTString(sXML,sb.ToString());
          }

          private static string transXMLStringThroughXSLTString(string sXML, string sXSLT)
          {
               //This is the logic of the application.
               XslTransform objTransform=new XslTransform();
               XmlDocument objDocument=new XmlDocument();
               StringWriter objStream=new StringWriter();

               //objDocument.Load(strAppPath+"BookFair.xml");
               objDocument.LoadXml(sXML);

               StringReader stream = new StringReader(sXSLT);
               XmlReader xmlR = new XmlTextReader(stream);

               objTransform.Load(xmlR,null,null);

               objTransform.Transform(objDocument,null,
                    objStream,null);
               return objStream.ToString().Replace(@"encoding=""utf-16""?>",@"encoding=""utf-8""?>");
          }

          public static string getDelimitedList(string[] nodeList)
          {
               return XMLRequests.utils.getDelimitedList(nodeList, ",");
          }
          public static string getDelimitedList(string[] nodeList, string delimiter)
          {
               System.Text.StringBuilder sb = new System.Text.StringBuilder();
               foreach(string s in nodeList)
               {
                    sb.Append(s.Trim());
                    sb.Append(delimiter);
               }
               string res = sb.ToString();
               if (res.Length > 0)
                    res = res.Substring(0,res.Length-1);
               return res;
          }
          public static string PrettyPrint(string XML)
          {
               String Result = "";
               try
               {
               

                    MemoryStream MS = new MemoryStream();
                    XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
                    XmlDocument D   = new XmlDocument();

                    // Load the XmlDocument with the XML.
                    D.LoadXml(XML);

                    W.Formatting = Formatting.Indented;

                    // Write the XML into a formatting XmlTextWriter
                    D.WriteContentTo(W);
                    W.Flush();
                    MS.Flush();

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

                    // Read MemoryStream contents into a StreamReader.
                    StreamReader SR = new StreamReader(MS);

                    // Extract the text from the StreamReader.
                    String FormattedXML = SR.ReadToEnd();

                    Result = FormattedXML;


                    MS.Close();
                    W.Close();
               }
               catch (Exception err)
               {
                    Exception e = new Exception(err.Message + " " + "XML Input: " + XML,err.InnerException);
                    throw(e);
               }

               return Result;
          }


     }
}






--------------- EXAMPLES.CS ---------------------

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using MSD.XmlLib; 

namespace XMLRequests.SampleCode
{
     /// <summary>
     /// Sample file for simple example of how to do typical XML with XmlBase
     /// </summary>
     public class example : XmlBase
     {
          public example()
          {

               /*
                * You can use this code like this:
                      XMLRequests.SampleCode.example ex = new XMLRequests.SampleCode.example();
                    ex.addItem("ack","bagaag","knieg");
                    ex.addItem("asdf","qwer","zxcv");
                    ex.items[0].item.value = "item";
                    ex.items[0].item.itemType = "itemType";
                    ex.items[0].value = "value";
                    ex.simpleList.listItem.Add("one");
                    ex.simpleList.listItem.Add("two");
                    ex.simpleList.listItem.Add("three");
                    string sResults = ex.Serialize();
               */
          }

          static public example DeserializeFile( string filename ) 
          { 
               return (example)XmlBase.DeserializeFile( filename, typeof( example ) ); 
          }
          
          static public example DeserializeString(string sXML)
          {
               return (example)XmlBase.DeserializeString(sXML,typeof( example ) );
          }

          [XmlAttribute] public string sampleAttribute = "";
          [XmlElement("sampleElement")] public string sampleElement = "";
          [XmlElement("items")] public itemsNode[] items = new itemsNode[]{new itemsNode()};
          [XmlElement("simpleList")] public simpleListNode simpleList = new simpleListNode();

          public int addItem(string item, string itemType, string itemValue)
          {
               //TODO:  There's got to be a better way to do this
               itemsNode[] tmpArr = new itemsNode[items.GetUpperBound(0) + 2];
               items.CopyTo(tmpArr,0);
               items = tmpArr;
               int i = items.GetUpperBound(0);
               items[i] = new itemsNode();
               items[i].item.value = item;
               items[i].item.itemType = itemType;
               items[i].value = itemValue;
               return i;
          }

          public class itemsNode
          {
               [XmlElement("item")] public itemNode item = new itemNode();
               [XmlElement("value")] public string value = "";

               public class itemNode
               {
                    [XmlAttribute] public string itemType = "";
                    [XmlText] public string value = "";
               }
          }
          public class simpleListNode
          {
               [XmlElement("listItem")] public System.Collections.ArrayList listItem = new System.Collections.ArrayList();
          }


     }
}


NameVersionSizeDateUser
example.cs122895/10/04 3:52 PM12.18.186.200
utils.cs152255/10/04 3:52 PM12.18.186.200
XmlBase.cs132455/10/04 3:52 PM12.18.186.200



Last Modified 3/5/05 4:58 AM

Hide Tools