Transforms XML data using an XSLT style sheet with C#

准备原始XML文件,如Person.xml:

 

<?xml version="1.0"  encoding="utf-8" ?>

<?xml-stylesheet type="text/xsl" href="Person.xslt" ?>

<xmlRoot>

  <PersonInfo>

    <Name>Adam</Name>

    <Adress>湖南长沙</Adress>

    <Gender>男</Gender>

  </PersonInfo>

  <PersonInfo>

    <Name>Eva</Name>

    <Adress>湖南长沙</Adress>

    <Gender>女</Gender>

  </PersonInfo>

</xmlRoot>



 

 

准备xslt文件,如Person.xslt文件:

此处有几点说明xsl:output节点的 method 属性可以指定输出的格式如html,xml,text等,这里指定输出为html

 

<?xml version="1.0" encoding="utf-8"?>

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

    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"

>

  <xsl:output method="html" indent="yes"   doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>

  <xsl:template match="/">

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

      <head>

        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

        <title>Elfin – Daily Report</title>

        <style type="text/css">

          table {

          border: 1px solid black;

          border-collapse: collapse;

          }

          table thead tr th {

          border: 1px solid black;

          padding: 3px;

          background-color: #cccccc;

          }



          table tbody tr td {

          border: 1px solid black;

          padding: 3px;

          }

        </style>

      </head>

      <body style="font-family: Tahoma, Verdana, Helvetica;">

        <table >

          <tr>

            <td>姓名</td>

            <td>地址</td>

            <td>性别</td>

          </tr>

          <xsl:for-each select="/xmlRoot/PersonInfo">

            <tr>

              <td>

                <xsl:value-of select="Name"/>

              </td>

              <td>

                <xsl:value-of select="Adress"/>

              </td>

              <td>

                <xsl:value-of select="Gender"/>

              </td>

            </tr>

          </xsl:for-each>

        </table>

      </body>

    </html>

  </xsl:template>

</xsl:stylesheet>



 

 

C#的转换代码:

 

  XmlDocument XmlDoc = new XmlDocument(); XmlDoc.Load("Person.xml");//原始xml文档

            Stream stream = File.Open("Person.xslt", FileMode.Open); XPathDocument xslDoc = new XPathDocument(stream);//xpath文档

            XslCompiledTransform xslt = new XslCompiledTransform(true);//Transforms XML data using an XSLT style sheet

            MemoryStream outStream = new MemoryStream();

            xslt.Load(xslDoc);

            xslt.Transform(XmlDoc, null, outStream);

            StringBuilder sb = new StringBuilder(HttpUtility.HtmlEncode(Encoding.UTF8.GetString(outStream.GetBuffer())));

            string html = sb.Replace("<", "<").Replace(">", ">").Replace(""", "\"").Replace("&", "&").Replace("\u0000", "").ToString();

 

 

你可能感兴趣的:(transform)