0

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>.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
teardrop
  • 545
  • 3
  • 9
  • 18
  • Possible duplicate : http://stackoverflow.com/questions/2920142/how-to-add-xmlnamespace-to-a-xmldocument – Ermiar Jan 25 '16 at 13:47
  • I tried but there is an error says that: "An object reference is required for the non-static field, method, or property 'XmlDocument.DocumentElement'" @Ermiar – teardrop Jan 25 '16 at 14:02

1 Answers1

0

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");
Ermiar
  • 1,078
  • 13
  • 20
  • It works, but all kind of these elements must have a namespace in their attributes. I think I have to use this recommendation. Thanks! @Ermiar – teardrop Jan 25 '16 at 18:10