ASP.NET Tutorial/XML/XslTransform

Материал из .Net Framework эксперт
Версия от 11:57, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Display data from database in asp:Xml with xml transformation

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="XmlDataSet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    
      <div class="Box">
        <asp:Button ID="cmdDataSetToXml" runat="server" Text="Display DataSet as XML" OnClick="cmdDataSetToXml_Click" Width="185px"/>
        <asp:Xml ID="XmlControl" runat="server" EnableViewState="False"></asp:Xml><br />
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Xml;
public partial class XmlDataSet : System.Web.UI.Page
{
  protected void cmdDataSetToXml_Click(object sender, EventArgs e)
  {
    string connectionString =
        WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
    string SQL = "SELECT * FROM authors WHERE city="Oakland"";
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(SQL, con);
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet("AuthorsDataSet");
    con.Open();
    adapter.Fill(ds, "AuthorsTable");
    con.Close();
    XmlDataDocument dataDoc = new XmlDataDocument(ds);
    XmlControl.XPathNavigator = dataDoc.CreateNavigator();
        XmlControl.TransformSource = "Data.xsl";
  }
}

File: Data.xsl
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
<xsl:template match="AuthorsDataSet">
   <h1>The Author List</h1>
      <xsl:apply-templates select="AuthorsTable"/>
   <i>Created through XML and XSLT</i>
</xsl:template>
<xsl:template match="AuthorsTable">
<b>Name: </b><xsl:value-of select="au_lname"/>, <xsl:value-of select="au_fname"/>
<br/>
<b>Phone: </b> <xsl:value-of select="phone"/>
</xsl:template>
</xsl:stylesheet>

File: Web.config
<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="Pubs" connectionString="Data Source=localhost\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Pubs;"/>
  </connectionStrings>
</configuration>


Read the transformed result of XslTransform and output the result (VB.net)

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.XPath" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<script runat="server">
   sub Page_Load(Sender as Object, e as EventArgs)
      Dim objReader as New XmlTextReader(Server.MapPath("Data.xml"))
      
      Dim objDoc as XPathDocument = new XPathDocument(objReader)
      
      Dim objXSLT As XslTransform = New XslTransform()
      dim objWriter as XmlTextWriter = new XmlTextWriter(Server.MapPath("output.html"), nothing)
      try
         objXSLT.Load(Server.MapPath("Data.xsl"))
         dim objReader2 as XmlReader = objXslT.Transform(objDoc, nothing)
         While objReader2.Read()
            Response.Write("<b>" & objReader2.Name & "</b> " & _
               objReader2.Value & "<br>")
         End While
      catch ex As Exception        
         Response.Write(ex.Message)
      finally
         objReader.Close
         objWriter.Close
      end try
   end sub   
</script>
<html><body>
</body></html>

File: Data.xml

<?xml version="1.0"?>
<bookstore>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
</bookstore>
File: Data.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:op="x-schema:books.xdr"
   version="1.0" >
   <xsl:template match="op:bookstore">
      <HTML><BODY>
      <TABLE width="450">
      <TR>
         <TD><b>Title</b></TD>
         <TD><b>Price</b></TD>
      </TR>
      <xsl:apply-templates select="op:book"/>
      </TABLE>
      </BODY></HTML>
   </xsl:template>
   <xsl:template match="op:book">
      <TR>
         <TD><xsl:value-of select="op:title"/></TD>
         <TD><xsl:value-of select="op:price"/></TD>
      </TR>
   </xsl:template>
</xsl:stylesheet>


Transform XML document to HTML

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="XmlToHtml" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Xml;
public partial class XmlToHtml : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    string xslFile = Server.MapPath("Data.xslt");
    string xmlFile = Server.MapPath("Data.xml");
    string htmlFile = Server.MapPath("Data.htm");
    XslTransform transf = new XslTransform();
    transf.Load(xslFile);
    transf.Transform(xmlFile, htmlFile);
    XPathDocument xdoc = new XPathDocument(new XmlTextReader(xmlFile));
    XPathNavigator xnav = xdoc.CreateNavigator();
    XmlReader reader = transf.Transform(xnav, null);
    reader.MoveToContent();
    Response.Write(reader.ReadOuterXml());
    reader.Close();
    }
}
File: Data.xml
<?xml version="1.0"?>
<Data>
   <DVD ID="1" Category="Category 1">
      <Title>title 1</Title>
      <Director>directory 2</Director>
      <Price>1</Price>
      <Starring>
         <Star>star 1</Star>
         <Star>star 2</Star>
      </Starring>
   </DVD>
   <DVD ID="2" Category="Category 2">
      <Title>title 2</Title>
      <Director>directory 2</Director>
      <Price>2</Price>
      <Starring>
         <Star>star 3</Star>
         <Star>star 4</Star>
      </Starring>
   </DVD>
</Data>

File: Data.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml"/>
  <xsl:template match="/">
    <xsl:element name="Movies">
      <xsl:apply-templates select="//DVD" />
    </xsl:element>
  </xsl:template>
  <xsl:template match="DVD">
    <xsl:element name="{name()}">
      <xsl:attribute name="ID">
        <xsl:value-of select="@ID"/>
      </xsl:attribute>
      <xsl:attribute name="Title">
        <xsl:value-of select="Title/text()"/>
      </xsl:attribute>
      <xsl:apply-templates select="Starring" />
    </xsl:element>
  </xsl:template>
  <xsl:template match="Starring">
    <xsl:element name="Stars">
      <xsl:attribute name="Name">
        <xsl:value-of select="Star/text()"/>
      </xsl:attribute>
    </xsl:element>
  </xsl:template>
  
</xsl:stylesheet>


Use XslTransform to trasnform XML data to HTML file (VB.net)

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.XPath" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<script runat="server">
   sub Page_Load(Sender as Object, e as EventArgs)
      Dim objReader as New XmlTextReader(Server.MapPath("Data.xml"))
      
      Dim objDoc as XPathDocument = new XPathDocument(objReader)
      Dim objNav as XPathNavigator = objDoc.CreateNavigator()
      
      Dim objXSLT As XslTransform = New XslTransform()
      dim objWriter as XmlTextWriter = new XmlTextWriter(Server.MapPath("output.html"), nothing)
      try
         objXSLT.Load(Server.MapPath("Data.xslt"))
         objXSLT.Transform(objDoc, nothing, objWriter)
         Response.Write("File written successfully")
      catch ex As Exception        
         Response.Write(ex.Message)
      finally
         objReader.Close
         objWriter.Close
      end try
   end sub   
</script>
<html><body>
</body></html>

File: Data.xml

<?xml version="1.0"?>
<bookstore>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
  <book genre="asdf">
    <title>asdf</title>
    <author>
      <first-name>asdf</first-name>
      <last-name>asdf</last-name>
    </author>
    <price>asdf</price>
  </book>
</bookstore>
File: Data.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:op="x-schema:books.xdr"
   version="1.0" >
   <xsl:template match="op:bookstore">
      <HTML><BODY>
      <TABLE width="450">
      <TR>
         <TD><b>Title</b></TD>
         <TD><b>Price</b></TD>
      </TR>
      <xsl:apply-templates select="op:book"/>
      </TABLE>
      </BODY></HTML>
   </xsl:template>
   <xsl:template match="op:book">
      <TR>
         <TD><xsl:value-of select="op:title"/></TD>
         <TD><xsl:value-of select="op:price"/></TD>
      </TR>
   </xsl:template>
</xsl:stylesheet>