I'm trying to create an xml file. I already set the document and have a result with Xmlwriter when printing to console but when it comes to having an actual .xml file on my desktop I always end up with empty files. Clearly I'm missing something or forgetting something but can't tell on my own.
Below is the piece of my code where it all happens (not).
public void button1_Click(object sender, EventArgs e)
{
XmlDocument dddxml = new XmlDocument();
//XmlDeclaration xmldecl;
//xmldecl = dddxml.CreateXmlDeclaration("1.0", null, null);
//xmldecl.Encoding = "UTF-8";
//xmldecl.Standalone = "yes";
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
StringBuilder builder = new StringBuilder();
writer = XmlWriter.Create(builder, settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
BlockSelect(0);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
Console.WriteLine(builder.ToString());
writer = XmlWriter.Create("DddXml.Xml", settings);
dddxml.Save(writer);
File.Create(path);//declared elsewhere, valid file location string
}
You have created new XmlDocument here:
XmlDocument dddxml = new XmlDocument();
But you haven't populated it in the rest of the code and in fact you're not using it and writing xml to string builder using WriteStartDocument and WriteEndElement methods of XmlWriter.
Thus your dddxml remains empty, so when you're trying to save it like this:
dddxml.Save(writer);
, there is nothing to save and you're getting empty file.
So you have to choose - will you use XmlDocument or XmlWriter to create and save your xml.
As commented by #Charles Mager, File.Create() just makes an empty file.
You can try to write directly to the file instead of using StringBuilder. Here's a sample to directly write to the file using the XmlWriter:
XmlWriter writer = XmlWriter.Create("C:\\ddxml.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
See that the file is written on C:\ddxml.xml.
If you want you can also use LINQ, it's easier :
XDocument doc = new XDocument();
XNamespace ns = "";
doc.Add(new XElement(ns + "root"));
doc.Save(#"C:\DddXml.Xml");
Related
I have a function that translates a xml file using a xsl style sheet. It does the job fine; but when I want to delete that transformed file sometimes I get the following error: System.IO.IOException: The process cannot access the file
The function is like this:
XslTransform transform = new XslTransform();
transform.Load('xsl_style_sheet');
transform.Transform('fullpath/xmlfilename','fullpath/transformedFileName')
XElement xEle = XElement.Load('fullpath/transformedFileName');
I do what ever with the xEle and in the end I want to delete the 'fullpath/transformedFileName' but some times i get the dreaded System.IO.IOException: The process cannot access the file
Can any one please help. A million thanks
Use the XslCompiledTranform class (XslTranform is obsolete ) and the overload on Transform that accepts an XmlReader and XmlWriter. You can call Dispose on them, they will take care of closing and disposing the underlying stream.
// Load the style sheet.
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("xsl_style_sheet");
// Create the writer.
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
using(XmlWriter writer = XmlWriter.Create("fullpath/transformedFileName", settings))
{
using(XmlReader reader = XmlReader.Create("fullpath/xmlfilename"))
{
reader.MoveToContent();
xslt.Transform(reader, writer);
}
}
using(XmlReader reader = XmlReader.Create("fullpath/transformedFileName"))
{
XElement xEle = XElement.Load(reader);
// do all other stuff you need to do here
// after this the file will be closed
}
I have an xmlwriter object used in a method. I'd like to dump this out to a file to read it. Is there a straightforward way to do this?
Thanks
Use this code
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Add a price element.
XmlElement newElem = doc.CreateElement("price");
newElem.InnerText = "10.95";
doc.DocumentElement.AppendChild(newElem);
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter(#"C:\data.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
As found on MSDN: http://msdn.microsoft.com/en-us/library/z2w98a50.aspx
One possibility is to set the XmlWriter to output to a text file:
using (var writer = XmlWriter.Create("dump.xml"))
{
...
}
Need to generate an html report from XML and corresponding XSL butI have to use memorystream instead of IO File write on server directories. For the most part I managed to create an xml
MemoryStream ms = new MemoryStream();
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
using(XmlWriter writer = XmlWriter.Create(ms,wSettings))
{
/**
creating xml here
**/
writer.Flush();
writer.Close();
}
return ms; // returning the memory stream to another function
// to create html
// This Function creates
protected string ConvertToHtml(MemoryStream xmlOutput)
{
XPathDocument document = new XPathDocument(xmlOutput);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlOutput);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(reportDir + "MyXslFile.xsl");
transform.Transform(xDoc, null, writer);
xmlOutput.Position = 1;
StreamReader sr = new StreamReader(xmlOutput);
return sr.RearToEnd();
}
Somewhere along the line I am messing up with creating the HTML Report and cant figure out how to send that file to client end. I dont have much experience working with memorystream. So, any help would be greatly appreciated. Thank you.
You're completely bypassing your transform here:
// This Function creates
protected string ConvertToHtml(MemoryStream xmlOutput)
{
XPathDocument document = new XPathDocument(xmlOutput);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlOutput);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(reportDir + "MyXslFile.xsl");
transform.Transform(xDoc, null, writer);
// These lines are the problem
//xmlOutput.Position = 1;
//StreamReader sr = new StreamReader(xmlOutput);
//return sr.RearToEnd();
return writer.ToString()
}
Also, calling Flush right before you call Close on a writer is redundant as Close implies a flush operation.
It is not clear to me what you want to achieve but using both XmlDocument and XPathDocument to load from the same memory stream does not make sense I think. And I would set the MemoryStream to Position 0 before loading from it so either have the function creating and writing to the memory stream ensure that it sets the Position to zero or do that before you call Load on the XmlDocument or before you create an XPathDocument, depending on what input tree model you want to use.
how we can create new xml file by C# in the following situation:
its winform.
our xml code is in a string str = "<><><><>...etc"
now i want to create an xml file myxml.xml which contains everything in str,
please answer in the context and thanks...
need simple source code
XmlDocument.LoadXml
using System;
using System.Xml;
public class Sample {
public static void Main() {
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>"); //Your string here
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
}
Hi how about creating a method just for this:
private static void CreateXMLFile(string xml, string filePath)
{
// Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml); //Your string here
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter(filePath, null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
If the only thing you want to do is to save the string as a file (and you don't want to do do XML-specific stuff like checking well-formedness or automatic indenting), you can simply use File.WriteAllText().
How do I work with an xml file that when updating it, after saving the commented lines would still be present.
Here's my code snippet for saving the file:
public static void WriteSettings(Settings settings, string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
TextWriter writer = new StreamWriter(path);
serializer.Serialize(writer, settings);
writer.Close();
}
I'm not sure I understand you requirement. I would say don't use XmlSerializer because that's designed for creating serialized versions of objects in XML form. Objects don't have XML comments in them, so the XML generated for the object won't generate any comments. If you want to deal with pure XML, just use a simple XML parsing class, rather than one designed for serializing classes as XML documents:
string myXml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
"<!-- This is a comment -->" + Environment.NewLine +
"<Root><Data>Test</Data></Root>";
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.PreserveWhitespace = true;
xml.LoadXml(myXml);
var newElem = xml.CreateElement("Data");
newElem.InnerText = "Test 2";
xml.SelectSingleNode("/Root").AppendChild(newElem);
System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings();
xws.Indent = true;
using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(Console.Out, xws))
{
xml.WriteTo(xw);
}
This code will overwrite xml file completely. In order to keep comments in existing file you have to read it first, then update and save.