1

我目前正在使用以下代码运行实时“内存中”XSLT 转换

XmlDocument XmlDoc = new XmlDocument();
XmlDoc.LoadXml(DS.GetXml());
XslCompiledTransform XsltTranformation = new XslCompiledTransform();
XsltTranformation.Load(@"C:\Users\maskew\Desktop\XSLTMapping.xsl");
Stream XmlStream = new MemoryStream();
XmlDoc.Save(XmlStream); //Stream is still blank after this line
XmlReader XmlRdr = XmlReader.Create(XmlStream);
MemoryStream stm = new MemoryStream();
XsltTranformation.Transform(XmlRdr, null, stm);
stm.Position = 1;
StreamReader sr = new StreamReader(stm);
string Output = sr.ReadToEnd();
Output = Output.Substring(2);
XmlDoc.LoadXml(Output);
XmlWriter XmlWrtr = XmlWriter.Create(@"C:\Users\maskew\Desktop\XmlMapping.xml");
XmlDoc.WriteTo(XmlWrtr);
XmlWrtr.Flush();
XmlWrtr.Close();

但是,当我在第 6 行将文件从 XmlDocument 移动到 MemoryStream 时,流在检查时不包含任何内容,从而阻止了整个程序的运行。

有谁知道为什么会发生这种情况?

更新:流现在包含信息,但是 XmlReader 对象仍然没有收到任何信息。

4

3 回答 3

3

尝试简单化

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(DS.GetXml());

// Create a writer for writing the transformed file.
XmlWriter writer = XmlWriter.Create(@"C:\Users\maskew\Desktop\XmlMapping.xml");

// Create and load the transform with script execution enabled.
XslCompiledTransform transform = new XslCompiledTransform();
XsltSettings settings = new XsltSettings();
settings.EnableScript = true;
transform.Load(@"C:\Users\maskew\Desktop\XSLTMapping.xsl", settings, null);

// Execute the transformation.
transform.Transform(xmlDoc, writer);
于 2012-08-10T08:07:18.580 回答
1
Stream XmlStream = new MemoryStream();

里面怎么会有东西?您正在构建一个空的 memoryStream ...

编辑 :

您应该尝试使用“使用”说明 (http://msdn.microsoft.com/fr-fr/library/yh598w02) 来澄清它。基本上,StreamReader、MemeryStream 等类实现了 IDisposable 接口。如果你用 using 包装它们,它会自动为你处理对象。

于 2012-08-10T07:58:42.377 回答
1

尝试刷新和重置流:

XmlDoc.Save(XmlStream);
XmlStream.Flush();
XmlStream.Position = 0;
XmlReader XmlRdr = XmlReader.Create(XmlStream);
于 2012-08-10T08:00:48.697 回答