Wednesday, October 13, 2010

How to transform XML file to differently formated XML file XSLT


Demo:

Download supported files:

Code:
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    string xml = this.Transform(Server.MapPath("~/Companies.xml"), Server.MapPath("~/CompaniesXml.xsl"));
    this.Response.Clear();
    this.Response.ContentType = "text/xml";
    this.Response.Write(xml);
    this.Response.End();
}
public string Transform(string sXmlPath, string sXslPath)
{
    XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
    XslTransform myXslTrans = new XslTransform();
    myXslTrans.Load(sXslPath);
    StringBuilder output = new StringBuilder();
    using (XmlTextWriter myWriter = new XmlTextWriter(new StringWriter(output)))
    {
        myXslTrans.Transform(myXPathDoc, null, myWriter);
        myWriter.Close();
    }
    return output.ToString();
}
XML file - Companies.xml
<companies>
  <company>
    <name>Mirosoft Ltd</name>
    <address1>Microsoft Campus</address1>
    <address2>Some avenue</address2>
    <city>Reading</city>
    <county>Berkshire</county>
    <postcode>RG6 1WG</postcode>
    <country>United Kingdom</country>
  </company>
  <company>
    <name>Tesco</name>
    <address1>65</address1>
    <address2> Nicholsons Walk</address2>
    <city>Maidenhead</city>
    <county>Bukinghamshire</county>
    <postcode>SL6 1LL</postcode>
    <country>United Kingdom</country>
  </company>
  <company>
    <name>Tesco</name>
    <address1>Off Alexander Road</address1>
    <address2>Park Road</address2>
    <city>City of London</city>
    <county>London</county>
    <postcode>TW3 1JT‎</postcode>
    <country>United Kingdom</country>
  </company>
</companies>
 XSLT file - CompaniesXml.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <companies>
      <xsl:apply-templates />
    </companies>
  </xsl:template>
  <xsl:template match="company">
    <company>
      <xsl:attribute name="name">
        <xsl:value-of select="name"/>
      </xsl:attribute>
      <xsl:attribute name="address1">
        <xsl:value-of select="address1"/>
      </xsl:attribute>
      <xsl:attribute name="address2">
        <xsl:value-of select="address2"/>
      </xsl:attribute>
      <xsl:attribute name="city">
        <xsl:value-of select="city"/>
      </xsl:attribute>
      <xsl:attribute name="postcode">
        <xsl:value-of select="postcode"/>
      </xsl:attribute>
      <xsl:attribute name="country">
        <xsl:value-of select="country"/>
      </xsl:attribute>
    </company>
  </xsl:template>
</xsl:stylesheet>

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...