I am using an api that returns text in XML that I am saving to an XML file.
Whenever I am trying to display the information to a datagridview. But I get an error saying the file is already open and being used. Here is the code that receives the text, saves it to the XML and tries to display it to the datagrid.
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseContent);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
// Save the document to a file and auto-indent the output.
XmlWriter writer = XmlWriter.Create("ResponseContent.xml", settings);
doc.Save(writer);
XmlReader xmlFile = XmlReader.Create(#"C:\Users\Tyler\Documents\Repo\New Trunk\WalmartSmiles\WalmartSmiles\bin\Debug\ResponseContent.xml", new XmlReaderSettings());
DataSet dataSet = new DataSet();
//Read xml to dataset
dataSet.ReadXml("ResponseContent.xml");
//Pass empdetails table to datagridview datasource
dataGridView1.DataSource = dataSet.Tables["ns2:feed"];
//Close xml reader
xmlFile.Close();
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];
Simple way of pass data to dataGridView
Usually when this happens, look for other things in your code that have also opened, read, written, or done anything with that file, and close them!
// Save the document to a file and auto-indent the output.
XmlWriter writer = XmlWriter.Create("ResponseContent.xml", settings);
doc.Save(writer);
writer.Close();
Related
**
I want to add XML schema and XML element together in same file. Because this xml file we will need to generate through C# based on specific record. So, i am looking some code help how can i write together XMLSchema and XML element in same file and inside same element. Please check attachment.
<Survey>
**Here i want XML schema**
**Here i want XML element**
</Survey>
Working Code Example
SiteSurveyX siteSurveyX = new SiteSurveyX();
XmlTextReader reader = new XmlTextReader("c:\\temp\\TestSiteSchema.xsd");
//siteSurveyX.SurveySchema = XmlSchema.Read(reader, null);
XmlSchema myschema = XmlSchema.Read(reader, null);
string filePath = HelperFunctions.SurveyFilePath + routeName;
////Get all node record from DB
siteSurveyX.Survey = routeService.GetRouteDetailForXML(routeId, Convert.ToString(ddlRoute.Text), chkCurrentInterruption.Checked);
using (FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
lblStatus.Text = "Preparing file";
stream.Close();
stream.Dispose();
//Convert record in XML
XmlSerializer serializer = new XmlSerializer(typeof(SiteSurveyX));
using (StreamWriter writer = new StreamWriter(filePath, true))
{
serializer.Serialize(writer, siteSurveyX);
lblStatus.Text = "Ready";
}
}
It's done with this code.
while reading XML file which is converted to String.
my Code is as follows
StringBuilder sb = new StringBuilder();
string xmlVal=string.Empty;
using (var reader = SqlHelper.ExecuteXmlReader(Conn, CommandType.StoredProcedure, spName, ListParam.ToArray()))
{
while (reader.Read())
{
sb.AppendLine(reader.ReadOuterXml());
xmlVal = sb.ToString(); // You can get the xml as string here.
}
}
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, System.Text.Encoding.Unicode);
XmlDocument document = new XmlDocument();
document.LoadXml(xmlVal);
writer.Formatting = Formatting.Indented;
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
mStream.Position = 0;
StreamReader sReader = new StreamReader(mStream);
by entering to this code it showing the error there is an error in xml document(0,0), but the string have the XMLCollection (xmlVal)
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<CollectionlDetail>));
using (StreamReader rd = new StreamReader(mStream))
{
CollectionlDetailCol= xs.Deserialize(rd) as ObservableCollection<CollectionlDetail>;
}
I am currently running a live 'in-memory' XSLT transformation using the following code
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();
However, when I move the file from XmlDocument to MemoryStream in line 6 the stream contains nothing when checked and thus stopping the whole program from running.
Does anyone have any idea why this would be occuring?
UPDATED: The stream is containing information now, however the XmlReader object is receiving none of it still.
Try a simplyfying
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);
Try flushing and resetting the stream:
XmlDoc.Save(XmlStream);
XmlStream.Flush();
XmlStream.Position = 0;
XmlReader XmlRdr = XmlReader.Create(XmlStream);
Stream XmlStream = new MemoryStream();
How there can be something in it ? You are constructing an empty memoryStream...
EDIT :
You should try to clarify it by using the 'using' instruction (http://msdn.microsoft.com/fr-fr/library/yh598w02). Basically, class like StreamReader, MemeryStream, etc.. implement the IDisposable interface. If you wrap them with using, it will dispose the object automatically for you.
I have created an xml document and an xslt document and now i want to create a word doc/rtf using these through using c#.
I have found the following code on the internet however I can't find a way to use it because I'm not using datasets. I just want the program to read the xml and the xslt combine the two and create a word document
Any help would be really appreciated
DataSet ds;
XmlDataDocument xmlDoc;
XslCompiledTransform xslTran;
XmlElement root;
XPathNavigator nav;
XmlTextWriter writer;
try
{
//Create the DataSet from the XML file
ds = new DataSet();
ds.ReadXml("Employee.xml");
//Create the XML from the DataSet
xmlDoc = new XmlDataDocument(ds);
//Load the XSLT for Transformation
xslTran = new XslCompiledTransform();
xslTran.Load("Employee.xslt");
//Determine the Root object in the XML
root = xmlDoc.DocumentElement;
//Create the XPath Navigator to navigate throuth the XML
nav = root.CreateNavigator();
//First delete the RTF, if already exist
if (File.Exists("Employee.rtf"))
{
File.Delete("Employee.rtf");
}
//Create the RTF by Transforming the XML and XSLT
writer = new XmlTextWriter("Employee.rtf", System.Text.Encoding.Default);
xslTran.Transform(nav, writer);
//Close the Writer after Transformation
writer.Close();
//Release all objects
writer = null;
nav = null;
root = null;
xmlDoc = null;
ds = null;
MessageBox.Show("Document created successfully.....");
}
catch (Exception ex)
{
writer = null;
nav = null;
root = null;
xmlDoc = null;
ds = null;
MessageBox.Show(ex.StackTrace);
}
}
Read http://msdn.microsoft.com/en-us/library/0610k0w4.aspx, it tells you how to use XslCompiledTransform. If you want to transform from a file and output a file then all you need is
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("stylesheet.xslt");
proc.Transform("input.xml", "output.rtf");
Here's a quick question I've been banging my head against today.
I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file.
Here's the current solution:
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();
Here's the original code:
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(#"<path to xsl file>");
transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null)
For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader.
My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML?
Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.
I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it.
EDIT:
Just tried following code and it worked perfectly:
BufferedStream stream = new BufferedStream(new MemoryStream());
stream.Write(Encoding.ASCII.GetBytes("<xml>foo</xml>"), 0, "<xml>foo</xml>".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();
You must select the root node. This doesn't use Datasets, but I use this function everyday and it works great.
System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument();
orgDoc.LoadXml(orgXML);
// MUST SELECT THE ROOT NODE
XmlNode transNode = orgDoc.SelectSingleNode("/");
System.Text.StringBuilder sb = new System.Text.StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);
System.IO.StringReader stream = new System.IO.StringReader(transformXML);
XmlReader reader = XmlReader.Create(stream);
System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform();
trans.Load(reader);
trans.Transform(transNode, writer);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
return doc;
please look it and use..
using (MemoryStream memStream = new MemoryStream())
{
memStream.Write(Encoding.UTF8.GetBytes(xmlBody), 0, xmlBody.Length);
memStream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(memStream))
{
// xml reader setting.
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings()
{
IgnoreComments = true,
IgnoreWhitespace = true,
};
// xml reader create.
using (XmlReader xmlReader = XmlReader.Create(reader, xmlReaderSettings))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(LoginInfo));
myObject = (LoginInfo)xmlSerializer.Deserialize(xmlReader);
}
}
}