2014-09-24 99 views
0

我已經閱讀並且找不到任何如何執行此操作的良好示例。我試圖創建編程文件看起來是這樣的:以編程方式創建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> 

我見過一些例子,但我不知道如何使它看起來完全一樣,與「樣式的xmlns:XLS =。 ...「以及表格和tr上的屬性。

有人可以幫我解決這個問題,或者發表一些很好的例子嗎?

+2

你有沒有看任何一個'XDocument','XmlDocument'或'XmlWriter'? – 2014-09-24 06:51:49

回答

2

你需要使用命名空間(也就是「XSL:」在元素的名稱)

我不會做整個事情給你,但這應該幫助你點在正確的方向: 你需要前綴元素名稱和使用命名空間屬性,像這樣:

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" /> 
+0

我個人會使用XmlWriter.WriteStartElement,XmlWriter.WriteAttribute,XmlWriter.WriteEndElement等,而不是在內存中創建一個文檔,然後序列化它。 – 2014-09-24 08:24:31