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");
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.
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();
I have one function which is
string fileToImport="C:\test.xml";
FileInfo fi = new FileInfo(fileToImport);
XmlDocument doc = new XmlDocument();
doc.Load(fileToImport);
This is point exact location of file.
But I want to use same function and import xml file from website.
For example I have below location.
http://testweb:1000/testdir/test.xml
Then I should open that location xml file and put in to the same way
FileInfo fi = new FileInfo(fileToImport);
XmlDocument doc = new XmlDocument();
doc.Load(fileToImport);
Anyone has best idea to get import this?
Thanks,
You should try
using (var client = new WebClient())
{
using (var reader = new StringReader(client.DownloadString("http://testweb:1000/testdir/test.xml")))
{
XmlDocument doc = new XmlDocument();
doc.Load(reader);
}
}
Also you can write this without WebClient&StringReader:
XmlDocument doc = new XmlDocument();
doc.Load("http://testweb:1000/testdir/test.xml");
More at https://msdn.microsoft.com/de-de/library/system.net.webclient(v=vs.110).aspx
I am modifying some legacy code to try to eliminate warnings. XmlDataDocument and XslTransform both generate warnings that they are obsolete. In the case of XslTransform the suggested replacement is XslCompiledTransform, but no replacement is suggested for XmlDataDocument.
How can I change this code to eliminate warnings in .NET 4:
var xmlDoc = new System.Xml.XmlDataDocument(myDataSet);
var xslTran = new System.Xml.Xsl.XslTransform();
xslTran.Load(new XmlTextReader(myMemoryStream), null, null);
var sw = new System.IO.StringWriter();
xslTran.Transform(xmlDoc, null, sw, null);
XDocument doc = new XDocument();
using (XmlWriter xw = doc.CreateWriter())
{
myDataSet.WriteXml(xw);
xw.Close();
}
XslCompiledTransform proc = new XslCompiledTransform();
using (XmlReader xr = XmlReader.Create(myMemoryStream))
{
proc.Load(xr);
}
string result;
using (StringWriter sw = new StringWriter())
{
proc.Transform(doc.CreateNavigator(), null, sw); // needs using System.Xml.XPath;
result = sw.ToString();
}
should do I think. Of course I have only used that MemoryStream for loading the stylesheet and the StringWriter for sending the transformation result to as you code snippet used those. Usually there are other input sources or output destinations like files, or streams or Textreader.
XMLDocument is really your main option. I'm not 100% sure what you're trying to do with the code block you've posted, but you can give something like this a shot:
public void DoThingsWithXml()
{
string strXdoc = src.GetTheXmlString(); // however it is you do it
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(strXdoc);
// The other things you need to do
}
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);
}
}
}