convert string to a xml file? - c#

How to save a well formed xml string to a xml file ?
Thanks in advance...
Hi All.... I got the answer
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("WellFormedXMLString");
xmlDoc.Save(#"drive:\name.xml");

What's wrong with simply writing your string to disk?
using (StreamWriter writer = new StreamWriter(#"C:\file.xml"))
{
writer.Write("Xml data");
writer.Flush();
}
or if you want to "test" it:
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(data);
}
catch
{
// Fix it
}
doc.Save(#"C:\file.xml");

You can write any string to disk like so:
File.WriteAllText(#"c:\myfile.xml", yourXmlString);
If you have a string that is not a well-formed xml string and you want to convert that to some other format, you will have to give us some example of what you want to do.

I am no C# programmer, but I guess you need something like this:
xmlwriter tutorial

Save the string straight onto the disk. No need to convert it into XML.

Why do you need xml if it's just a string ? You could save a text file with the variabele name, and the string inside as variable value.
for example
MyTextVar1.txt would contain "MyTestSTring"
then you could get the var by:
var mystring = GetFileAsString( "MyTextVar1.txt" );

The xml document is a text file itself. you only need to change its extension.

Related

XmlWriter trimming my string

I am trying to return an XML string as a CLOB from Oracle stored procedure to C# string.
Then I am write this string to a file using XmlWriter class.
My code looks like following:
string myString= ((Oracle.ManagedDataAccess.Types.OracleClob)(cmd.Parameters["paramName"].Value)).Value.ToString();
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
var stream = new MemoryStream();
var writer = XmlWriter.Create(stream);
writer.WriteRaw(myString);
stream.Position = 0;
var fileStreamResult = File(stream, "application/octet-stream", "ABCD"+fileName+".xml");
return fileStreamResult;
When I checked my CLOB output it returns completely to myString.
When I check my end result, XML file is trimmed at the end.
My string will be huge for ex: Length of 3382563 and more.
Is there any setting for XmlWriter to write the complete string to file.
Thanks in advance.
Sounds like all you want to do is grab some string value out of your Database, and write that string value in a text file. The string being xml does not actually force you into using an XML specific class or method unless you want to do XML specific operations, which I do not see in your snippet. Therefore, I suggest you simply grab the string value and spit it out in a file in the easiest way.
string myString = " blah blah blah keep my spaces ";
using (StreamWriter sw = new StreamWriter(#"M:\StackOverflowQuestionsAndAnswers\XMLWriterTrimmingString_45380476\bin\Debug\outputfile.xml"))
{
sw.Write(myString);
}

Convert string to XML using .Net

I store the XML output to String and Again convert this string to XML .I successfully convert XML output to String, but i got problem again converting string to XML.
sample code:
webservice.Service1 objService1 = new webservice.Service1();
String s = objService1.HelloWorld(); //Convert XML output into String
XmlDocument xd = new XmlDocument();
xd.LoadXML(s);
I use LoadXML() method, but i got error
Data at the root level is invalid. Line 1 position 1.
Its grateful, if any body give right code to convert String To XML in c#.
Thank you,
You should use XDocument. XDocument is better than XMLDocument. It is very efficient, simple and easy to use.
Your code :
webservice.Service1 objService1 = new webservice.Service1();
String s = objService1.HelloWorld(); //Convert XML output into String
XmlDocument xd = new XmlDocument();
xd.LoadXml(s);
Solution:
XDocument xd = XDocument.Parse(s);
XmlDocument xd = new XmlDocument();
xd.LoadXml("<root>123</root>");
It works.
You should print the s value and check it is a valid xml string.

Write XML in a string c#

I was wondering how I could , when I get the xml write it in a string ?
Because when I do this :
{
XDocument xdoc = XDocument.Load("MYURL");
string textresult = xdoc.Root.ToString();
Label_RequestResult.Text = textresult;
}
my Label_RequestResult.text will be equal to the value of the node of the XML.
I would like to actually return the whole xml structure .
Is this posible ?
Thanks for helping.
In my case string textresult = xdoc.ToString(); did the job.
I got the whole structure, even with spaces and line breaks.
I think it should something like this: have you tried already?
string textresult = xdoc.Root.Value();

Using XDocument to write raw XML

I'm trying to create a spreadsheet in XML Spreadsheet 2003 format (so Excel can read it). I'm writing out the document using the XDocument class, and I need to get a newline in the body of one of the <Cell> tags. Excel, when it reads and writes, requires the files to have the literal string
embedded in the string to correctly show the newline in the spreadsheet. It also writes it out as such.
The problem is that XDocument is writing CR-LF (\r\n) when I have newlines in my data, and it automatically escapes ampersands for me when I try to do a .Replace() on the input string, so I end up with &#10; in my file, which Excel just happily writes out as a string literal.
Is there any way to make XDocument write out the literal
as part of the XML stream? I know I can do it by deriving from XmlTextWriter, or literally just writing out the file with a TextWriter, but I'd prefer not to if possible.
I wonder if it might be better to use XmlWriter directly, and WriteRaw?
A quick check shows that XmlDocument makes a slightly better job of it, but xml and whitespace gets tricky very quickly...
I battled with this problem for a couple of days and finally came up with this solution. I used XMLDocument.Save(Stream) method, then got the formatted XML string from the stream. Then I replaced the &#10; occurrences with
and used the TextWriter to write the string to a file.
string xml = "<?xml version=\"1.0\"?><?mso-application progid='Excel.Sheet'?><Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
xml += "<Styles><Style ss:ID=\"s1\"><Alignment ss:Vertical=\"Center\" ss:WrapText=\"1\"/></Style></Styles>";
xml += "<Worksheet ss:Name=\"Default\"><Table><Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"75\" /><Row><Cell ss:StyleID=\"s1\"><Data ss:Type=\"String\">Hello&#10;&#10;World</Data></Cell></Row></Table></Worksheet></Workbook>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml); //load the xml string
System.IO.MemoryStream stream = new System.IO.MemoryStream();
doc.Save(stream); //save the xml as a formatted string
stream.Position = 0; //reset the stream position since it will be at the end from the Save method
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string formattedXML = reader.ReadToEnd(); //fetch the formatted XML into a string
formattedXML = formattedXML.Replace("&#10;", "
"); //Replace the unhelpful &#10;'s with the wanted endline entity
System.IO.TextWriter writer = new System.IO.StreamWriter("C:\\Temp\test1.xls");
writer.Write(formattedXML); //write the XML to a file
writer.Close();

Putting date in front of xml file name

I have the following code:
XmlSerializer SerializeObj = new XmlSerializer(dirs.GetType());
TextWriter WriteFileStream = new StreamWriter(#"G:\project\tester.xml");
SerializeObj.Serialize(WriteFileStream, dirs);
WriteFileStream.Close();
I'm trying to put a date/time stamp in FRONT of the xml file name. Therefore, using this example, i'd have something like 0615_Tester.xml
Any ideas on how to do this? I want to make sure i can do date/time__[filename].xml and still specify it to be on my G:\
Thanks in advance.
This is Simply achieved with System.IO.Path:
string path = "G:\\projects\\TestFile.xml";
string NewPath = System.IO.Path.GetDirectoryName(path) +
System.IO.Path.DirectorySeperatorChar +
DateTime.Now.ToString() +
System.IO.Path.GetFileName(path);
You can add a using Reference to keep the Typing down, or Format the Date in any way you want as long as its a string. Using the DirectorySeperator Variable is reccommended, although you are probably programming for Windows If using .NET (Mono?)
Use string.Format - for example:
string dateString = "0615";
string fileName = string.Format(#"G:\project\{0}_tester.xml", dateString);
... = new StreamWriter(fileName);
Building up "dateString" should be trivial from DateTime.Now.
Try something like this:
string filePath = string.Format("G:\\project\\{0}tester.xml", Date.Now.ToString("DDMM"));
TextWriter WriteFileStream = new StreamWriter(filePath);
I'm assuming that the file already exists. So you will have to copy the file and delete the old one. Like this:
File.Copy(OldFileName, NewFileNameWithDate);
File.Delete(OldFileName);
string yourDateString = DateTime.Now.ToString(); // replace with any way you want to get your date string
string filename = "G:\\project\\" + yourDateString + "_tester.xml";
TextWriter WriteFileStream = new StreamWriter(filename);

Categories