这是一个很快的问题,我今天一直在抨击我的头脑.
我正在尝试将.Net数据集转换为XML流,使用内存中的xsl文件对其进行转换,然后将结果输出到新的XML文件.
这是目前的解决方案:
string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close();
这是原始代码:
BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@""); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null)
由于某些原因在transformer.Transform方法中,读者没有根节点,实际上读者没有从StreamReader中读取任何内容.
我的问题是这段代码有什么问题?其次,有没有更好的方法将数据集转换/转换/存储到XML?
编辑:两个答案都很有帮助,技术上aku更接近.然而,我倾向于在尝试两种解决方案后更接近Longhorn的解决方案.
我不确定,但似乎你没有在将流传递给XmlReader之前重置流中的位置.在尝试从中读取之前,尝试在流的开头搜索.在向它写入一些数据后,可能还需要关闭\ flush stream.
编辑:
只是尝试了下面的代码,它完美地工作:
BufferedStream stream = new BufferedStream(new MemoryStream()); stream.Write(Encoding.ASCII.GetBytes("foo "), 0, "foo ".Length); stream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(stream); XmlReader reader = XmlReader.Create(sr); while (reader.Read()) { Console.WriteLine(reader.Value); } stream.Close();