Reputation: 4550
I just learned about XSL and XSLT a few days ago and now I'm trying to put it to work based on a question I had earlier today (want to have formated XML displayed on my website).
Here is the code I'm trying (in a View):
XDocument xmlInput = XDocument.Parse(item.Action);
XDocument htmlOutput = new XDocument();
using (System.Xml.XmlWriter writer = xmlInput.CreateWriter())
{
// Load Transform
System.Xml.Xsl.XslCompiledTransform toHtml = new System.Xml.Xsl.XslCompiledTransform();
string path = HttpContext.Current.Server.MapPath("~/App_Data/xmlverbatimwrapper.xsl");
toHtml.Load(path);
// Execute
toHtml.Transform(xmlInput.CreateReader(), writer);
}
Response.Write(htmlOutput.ToString());
And it's giving me this error:
[InvalidOperationException: This operation would create an incorrectly structured document.]
Not sure if it's along the right lines, but I've tried modifying the writers settings so it can produce fragmented xml files with no luck (since it's readonly). Any ideas to get this working? Perhaps I'm going about completely the wrong approach? :)
Thanks for your help!
Upvotes: 0
Views: 1607
Reputation: 4550
I got the above code working by looking at this site
The code I ended up using (which was copied from the link above with a few changes for my specific situation) was:
String TransactionXML = item.Action;
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.IO.Stream xmlStream;
System.Xml.Xsl.XslCompiledTransform xsl = new System.Xml.Xsl.XslCompiledTransform();
ASCIIEncoding enc = new ASCIIEncoding();
System.IO.StringWriter writer = new System.IO.StringWriter();
// Get Xsl and XML
xsl.Load(HttpContext.Current.Server.MapPath("~/App_Data/xmlverbatimwrapper.xsl"));
xmlDoc.LoadXml(TransactionXML);
// Get the bytes
xmlStream = new System.IO.MemoryStream(enc.GetBytes(xmlDoc.OuterXml), true);
// Load Xpath document
System.Xml.XPath.XPathDocument xp = new System.Xml.XPath.XPathDocument(xmlStream);
// Perform Transform
xsl.Transform(xp, null, writer);
// output
Response.Write(writer.ToString());
Hope this helps someone! :)
Upvotes: 1
Reputation: 86774
Just a guess, but valid HTML is not necessarily valid XML, and you're using a class called XmlWriter. Without seeing your XSL and input XML it's kind of hard to figure out what's going. I suspect your output document is not well-formed XML.
I would guess you need to provide a different Writer implementation that can deal with HTML output.
Upvotes: 0