Search code examples
c#xmlxmldocument

Create a <xls:text></xsl:text> element programatically


When I want to create an element with xsl:name prefix in C#, it creates a element without xsl prefix. How can I create an element with specific prefix? I removed <xslt:stylesheet> header from xml file, but when I opened the xml file, Load method had thrown an exception about xsl prefix.

?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<table border="1">
    <thead>
        <tr>
            <!--<th>
                <span>
                    <xsl:text>HeaderSample</xsl:text>
                </span>
            </th>-->
        </tr>
    </thead>
    <tbody>
        <xsl:for-each select="result1">
            <xsl:for-each select="row">
                <tr>
                    <td>
                        <xsl:for-each select="HeaderSample">
                            <xsl:apply-templates/>
                        </xsl:for-each>
                    </td>                   
                </tr>
            </xsl:for-each>
        </xsl:for-each>
    </tbody>
</table>        
</xsl:stylesheet>
XmlDocument doc = new XmlDocument();
doc.Load("Template\\ResultItem.xml");

XmlNode headerElement = doc.LastChild.SelectSingleNode("table/thead/tr");

foreach (string h in Headers)
{
    XmlElement thElement = doc.CreateElement("th");
    XmlElement spanElement = doc.CreateElement("span");
    XmlElement xslTextElement = doc.CreateElement("xsl:text");

    xslTextElement.InnerText = h;

    spanElement.AppendChild(xslTextElement);
    thElement.AppendChild(spanElement);
    headerElement.AppendChild(thElement);
}                               

In the output there is no <xsl:text>...</xsl:text> but there is <text>...</text>.


Solution

  • You need to add the namespace of your element when creating the node if you want to have the prefix added in the XML output.

    Replace this line :

    XmlElement xslTextElement = doc.CreateElement("xsl:text");
    

    By :

     XmlElement xslTextElement = doc.CreateElement("xsl:text", "http://www.w3.org/1999/XSL/Transform");