问题
I have some XML in a XMLDocument
and I want to put it into a StringWriter
, but it always becomes empty(?) instead. I've tried inspecting the variables with debug, but I'm still clueless as to what's going on.
Here's what I have:
XmlDocument xmlInput = new XmlDocument();
/* after this executes, xmlInput has lots of data in it */
xmlInput.LoadXml(...);
XslCompiledTransform transform = new XslCompiledTransform();
/* I'm pretty sure Template.xslt is being found and loaded correctly */
transform.Load(Server.MapPath("/Files/Template.xslt"));
using (System.IO.StringWriter sb = new System.IO.StringWriter())
{
XmlWriterSettings xSettings = new XmlWriterSettings();
xSettings.ConformanceLevel = ConformanceLevel.Fragment;
xSettings.Encoding = Encoding.UTF8;
/* PROBLEM: After this line, StringWriter sb is {} */
using (XmlWriter xWriter = XmlWriter.Create(sb, xSettings))
{
transform.Transform(xmlInput, xWriter);
}
/* xmlText is empty string "" after this line */
String xmlText = sb.ToString();
/* ... does more stuff ... */
}
Can I have some help? I'm really not sure where to go from here to get this working.
EDIT: Even more investigation:
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
/* Prints lots of data to the screen */
Response.Write(xmlInput.InnerXml);
xmlInput.WriteTo(xmlTextWriter);
/* Doesn't print anything to the screen */
Response.Write(stringWriter.GetStringBuilder().ToString() );
}
}
BUT, flushing does the trick
xmlInput.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
/* prints lots of data */
Response.Write( stringWriter.GetStringBuilder().ToString() );
回答1:
It turns out that the XSLT file I was trying to apply required the XML to be wrapped in a certain element.
But the flush()
trick helped a lot.
来源:https://stackoverflow.com/questions/7561456/xml-stringwriter-empty