以编程方式创建具有属性的xml

时间:2014-09-24 06:30:40

标签: c# xml

我已经阅读过,我找不到任何有关如何做到这一点的好例子。我试图以编程方式创建的文件如下所示:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
  <head>
    <title> title here </title>
  </head>
  <body>
    <xsl:apply-templates />
  </body>
</html>
</xsl:template>
<xsl:template match="data">
<table width="400" border="1">
  <tr bgcolor="#a0acbc">
    <td></td>
    <td></td>
  </tr>
  <xsl:for-each select="row">
    <tr>
      <td>
        <xsl:value-of select="" />
      </td>
      <td>
        <xsl:value-of select="" />
      </td>
    </tr>
  </xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

我已经看过一些例子,但我不知道如何使它看起来完全像这样,使用“stylesheet xmlns:xls = ....”并使用表和tr上的属性。

有人可以帮我这个或者给我一些好的例子吗?

1 个答案:

答案 0 :(得分:2)

您需要使用名称空间(即元素名称中的&#34; xsl:&#34;)

我不会为你做整件事,但这应该有助于指明你正确的方向: 您需要在元素名称和属性前加上名称空间,如下所示:

using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace XSLCreator
{
   class Program
   {
      static void Main(string[] args)
      {
         XNamespace xsl = XNamespace.Get("http://www.w3.org/1999/XSL/Transform");

         var doc = new XDocument(
             new XElement(xsl + "stylesheet",
                 new XAttribute(XNamespace.Xmlns + "xsl", xsl),
                 new XAttribute("version", "1.0")
             )
         );

         var sw = new StreamWriter("test.xml");
         XmlWriter xw = new  XmlTextWriter(sw);
         doc.WriteTo(xw);
         xw.Close();
         sw.Close();
      }
   }
}

您将获得一个如下所示的xml文档:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" />
相关问题