I have this xsl:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:cf="http://AAA"
xmlns="http://AAA"
exclude-result-prefixes="cf">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/cf:Content">
<html>
<head>
<title>AAA</title>
</head>
<body>
Hello everybody
</body>
</html>
</xsl:template>
</xsl:stylesheet>
this xml:
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet href="myxsl.xslt" type="text/xsl"?>
<cf:Content xmlns:cf="http://AAA"
xmlns="http://AAA">
Hello.
</cf:Content>
The namespace referenced by the xml is an xsd of mine (validation is correct).
Well, is I open the xml file with a browser, the xslt works.
Now, I have this code:
string xml = "THE SAME XML OF THE XML FILE";
XslCompiledTransform transform = new XslCompiledTransform();
using (XmlReader xr =
XmlReader.Create("myxsl.xslt")) {
transform.Load(xr);
}
try {
using (StringWriter sw = new StringWriter())
using (StringReader sr = new StringReader(xml))
using (XmlReader xr = XmlReader.Create(sr)) {
transform.Transform(xr, new XsltArgumentList(), sw);
string html = sw.ToString();
this.Preview_Literal.Text = html;
}
} catch (Exception ex) {
throw ex;
}
Of course it get an exception:
Error: Data at the root level is invalid. Line 1, position 1. - Type: System.Xml.XmlException
What is the problem?
<?xml-stylesheet ...line?<xsl:output method="html" .../>instead of method="xml" is the right approach. And if you want to create HTML elements then remove thexmlns="http://AAA"from thexsl:stylesheetas HTML elements don't belong in that namespace. None of that explains the error you get but I suspect that is not caused by XSLT at all, rather simply happening when the input markup is parsed as XML. Can you post a stack trace? Where/how is thexmlvariable populated?