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> */
XML-RPC
Illustrates the XslTransform class
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example20_3.cs illustrates the XslTransform class */ using System; using System.Xml; using System.Xml.Xsl; using System.IO; public class Example20_3 { public static void Main() { // use an XmlTextReader to open an XML document XmlTextReader xtr = new XmlTextReader("Cust3.xml"); xtr.WhitespaceHandling = WhitespaceHandling.None; // load the file into an XmlDocuent XmlDocument xd = new XmlDocument(); xd.Load(xtr); // load an XSLT file XslTransform xslt = new XslTransform(); xslt.Load("Cust.xsl"); // perform the transformation in memory MemoryStream stm = new MemoryStream(); xslt.Transform(xd, null, stm); // and dump the results stm.Position = 1; StreamReader sr = new StreamReader(stm); Console.Write(sr.ReadToEnd()); // close the reader xtr.Close(); } } //File:Cust3.xml /* <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="Cust.xsl"?> <NewDataSet> <Customers> <CustomerID>ALFKI</CustomerID> <CompanyName>Alfreds Futterkiste</CompanyName> <ContactName>Maria Anders</ContactName> <ContactTitle>Sales Representative</ContactTitle> <Address>Obere Str. 57</Address> <City>Berlin</City> <PostalCode>12209</PostalCode> <Country>Germany</Country> <Phone>030-0074321</Phone> <Fax>030-0076545</Fax> </Customers> <Customers> <CustomerID>BONAP</CustomerID> <CompanyName>A Company</CompanyName> <ContactName>Laurence Lebihan</ContactName> <ContactTitle>Owner</ContactTitle> <Address>12, rue des Bouchers</Address> <City>Marseille</City> <PostalCode>13008</PostalCode> <Country>France</Country> <Phone>91.24.45.40</Phone> <Fax>91.24.45.41</Fax> </Customers> </NewDataSet> */ //File:Cust.xsl /* <?xml version="1.0" encoding="UTF-8"?> <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <body> <xsl:for-each select="/NewDataSet/Customers"> <p><h2>Customer</h2> <br><b><xsl:value-of select="CustomerID"/></b></br> <br><xsl:value-of select="CompanyName"/></br> <br><xsl:value-of select="ContactName"/></br></p> </xsl:for-each> </body> </html> */
Read command line input and do the xml xsl translation
using System; using System.Xml.Xsl; public class Transform { public static void Main(string [] args) { string source = args[0]; string stylesheet = args[1]; string destination = args[2]; XslTransform transform = new XslTransform(); transform.Load(stylesheet); // for .NET v 1.0 //transform.Transform(source, destination); // for .NET v 1.1 transform.Transform(source, destination, null); } }
Perform an XSL Transform
using System; using System.Xml; using System.Xml.Serialization; using System.IO; using System.Xml.Xsl; public class TransformXml { private static void Main() { XslTransform transform = new XslTransform(); // Load the XSL stylesheet. transform.Load("orders.xslt"); // Transform orders.xml into orders.html using orders.xslt. transform.Transform("orders.xml", "orders.html", null); } }
Use XslCompiledTransform
using System; using System.Xml.Xsl; class MainClass { public static void Main() { XslCompiledTransform transform = new XslCompiledTransform(); transform.Load("orders.xslt"); transform.Transform("orders.xml", "orders.html"); } }
Deserializes/Serializes an xml document back into an object
//New BSD License (BSD) //http://twitterxml.codeplex.com/license using System; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; namespace TwitterXml.Utilities { public class XmlSerializerHelper { /// <summary> /// Deserializes an xml document back into an object /// </summary> /// <param name="xml">The xml data to deserialize</param> /// <param name="type">The type of the object being deserialized</param> /// <returns>A deserialized object</returns> public static object Deserialize(XmlDocument xml, Type type) { XmlSerializer s = new XmlSerializer(type); string xmlString = xml.OuterXml.ToString(); byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString); MemoryStream ms = new MemoryStream(buffer); XmlReader reader = new XmlTextReader(ms); Exception caught = null; try { object o = s.Deserialize(reader); return o; } catch (Exception e) { caught = e; } finally { reader.Close(); if (caught != null) throw caught; } return null; } /// <summary> /// Serializes an object into an Xml Document /// </summary> /// <param name="o">The object to serialize</param> /// <returns>An Xml Document consisting of said object's data</returns> public static XmlDocument Serialize(object o) { XmlSerializer s = new XmlSerializer(o.GetType()); MemoryStream ms = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding()); writer.Formatting = Formatting.Indented; writer.IndentChar = ' '; writer.Indentation = 5; Exception caught = null; try { s.Serialize(writer, o); XmlDocument xml = new XmlDocument(); string xmlString = ASCIIEncoding.UTF8.GetString(ms.ToArray()); xml.LoadXml(xmlString); return xml; } catch (Exception e) { caught = e; } finally { writer.Close(); ms.Close(); if (caught != null) throw caught; } return null; } } }
Converts an XML string to an object
/* Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Text; using System.Xml.Serialization; namespace Utilities { /// <summary> /// Utility class for managing files /// </summary> public static class FileManager { /// <summary> /// Gets a files' contents /// </summary> /// <param name="FileName">File name</param> /// <returns>a string containing the file's contents</returns> public static string GetFileContents(string FileName) { try { return GetFileContents(FileName, 5000); } catch { throw; } } /// <summary> /// Gets a files' contents /// </summary> /// <param name="FileName">File name</param> /// <param name="TimeOut">Amount of time in ms to wait for the file</param> /// <returns>a string containing the file's contents</returns> public static string GetFileContents(string FileName, int TimeOut) { StreamReader Reader = null; int StartTime = System.Environment.TickCount; try { bool Opened = false; while (!Opened) { try { if (System.Environment.TickCount - StartTime >= TimeOut) throw new System.IO.IOException("File opening timed out"); Reader = File.OpenText(FileName); Opened = true; } catch (System.IO.IOException e) { throw e; } } string Contents = Reader.ReadToEnd(); Reader.Close(); return Contents; } catch { return ""; } finally { if (Reader != null) { Reader.Close(); Reader.Dispose(); } } } } /// <summary> /// Helps with serializing an object to XML and back again. /// </summary> public static class Serialization { /// <summary> /// Takes an XML file and exports the Object it holds /// </summary> /// <param name="FileName">File name to use</param> /// <param name="Object">Object to export to</param> /// <param name="ObjectType">Object type to export</param> public static void XMLToObject(string FileName, out object Object,Type ObjectType) { if (string.IsNullOrEmpty(FileName)) { throw new ArgumentException("File name can not be null/empty"); } try { string FileContent = FileManager.GetFileContents(FileName); Object = XMLToObject(FileContent,ObjectType); } catch { throw; } } /// <summary> /// Converts an XML string to an object /// </summary> /// <param name="XML">XML string</param> /// <param name="ObjectType">Object type to export</param> /// <returns>The object of the specified type</returns> public static object XMLToObject(string XML,Type ObjectType) { if (string.IsNullOrEmpty(XML)) { throw new ArgumentException("XML can not be null/empty"); } try { using (MemoryStream Stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(XML))) { XmlSerializer Serializer = new XmlSerializer(ObjectType); return Serializer.Deserialize(Stream); } } catch { throw; } } } }