Convert .txt to .xml - c#

I am looking for a way in C# to input a text file and output an xml. After some searching, I have found ways to input strings and output as xml, and by hand input some text into a C# source code, and output as xml, but not to import a text file and output. I need this as I have an application that saves some computer-specific info to a txt file. I would like to make a C# program that takes this .txt and outputs it as .xml . All .txt files will have the same format. If possible I would like it to output to something like:
<Data>
<Info>#</Info>
All the contents of the text file would output into the # area. Thank you for the help!

Assuming you need to add xml element for every line in txt, you can write similar to following (XLINQ).
String[] data = File.ReadAllLines("TextFile.txt");
XElement root = new XElement("root",
from item in data
select new XElement("Line",item));
root.Save("XmlFile.Xml");
Output
<root>
<Line>Hello</Line>
<Line>World</Line>
</root>

The following will open a file, read the contents, create a new XML document, and then save the results to the same path as the original, only with an XML extension.
var txt = string.Empty;
using (var stream = File.OpenText(pathToFile))
{
txt = stream.ReadToEnd();
}
var xml = new XDocument(
new XElement("Data",
new XElement("Info", txt)));
xml.Save(Path.ChangeExtension(pathToFile, ".xml"));

Related

load xml file after reading in string

I have read an xml file as a string due to cryptography.
string xmlString = System.IO.File.ReadAllText("../../liberal.xml");
//how to load xml document here?
XmlDocument xmlDo = new XmlDocument();
xmlDo.Load("../../liberal.xml");
The above code throws error and doesn't load.
XML file doesn't have any root elements and right now liberal XML file looks like this dasjkhf8dfkbhdflak3kjbdf+fafas(safasasdfjgdskalfguv.ng;FHSDAFKLASDF.
Couldn't load xml document with this data format. Only if I can load XML document I will be able to use their properties to add new values to the xml file.
Update1:
I decrypted the xml and placed in a string, but couldn't load the xml document with that string.
string retValue;
XmlDocument dec = new XmlDocument();
dec.Load(retValue);
retValue string has values like this.
<Product><Type>Metal</Type><Department>Foundry</Department></Product>
Error Message
Illegal characters in path.
Really appreciate any help with this.
You're using the XmlDocument.Load(string) method which accepts a path to an XML file. You need to use the XmlDocument.LoadXml(string) method which accepts any valid XML markup. Two completely different parameters. Example:
// XmlDocument.LoadXml(string)
string decryptedMarkup = "<Product><Type>Metal</Type>"
+ "<Department>Foundry</Department></Product>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(decryptedMarkup);
// XmlDocument.Load(string)
string pathToFile = "test.xml";
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.Load(pathToFile);
For further information, take a look at:
XmlDocument.Load(string)
String parameter:URL for the file containing the XML document to load. The URL can be either a local file or an HTTP URL (a Web address).
XmlDocument.LoadXml(string)String parameter:String containing the XML document to load.

How to read a local xml file into a string

In the root of my solution I have a XML file, which content I want to write to a string, because later I parse this string. What is the easiest way in WP8. I dont want to parse anything, just my string to have the content of the xml file, then I use this string the way I do now. Or the file needs to be txt with xml inside, I dont care. Thanks!
how about
using System.Xml.Linq;
// load the file using;
var xDocument = XDocument.Load(#"C:\MyFile.xml");
// convert the xml into string
string xml = xDocument.ToString();
You may want to try this :
StreamResourceInfo strm = Application.GetResourceStream(new Uri("/myProject;component/States.xml",UriKind.Relative));
StreamReader reader = new StreamReader(strm.Stream);
string xmlData = reader.ReadToEnd();
[Nokia developer community wiki: Parse Local XML file in Windows Phone]
or another possible way as shown in this other SO question : Windows Phone 8 - reading and writing in an existing txt file in the project

how to edit utf-16 xml file if it have string line after the end of the main Node

I have Special XML file with utf-16 encoding type. this file used to store data and I need to Edit it Using C# windows forms Application
<?xml version="1.0" encoding="utf-16"?>
<cProgram xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="b0eb0c7e-f4de-4bc7-9e62-7a086a8c2fn8" Version="16.01" xmlns="cProgram">
<Serie>N </Serie>
<No>123456</No>
<type>101</type>
<Dataset4>larg data here 2 million char</Dataset4>
</cProgram>123456FF896631N 4873821012013-06-14
the problem is: it is not ordinary XML file
Because at the very End of the file I have a string line too, and that would give this error
Data at the root level is invalid. Line x, position x
when I try to load it as xml file
I tried to temporary replace the last line and get it back after I change the inner text, and it works But I lost the declaration Line and I didn't find a way to rewrite it when I have that text at the end of the file !_
so I need to change the InnerText of (Serie) and (No) nodes
but I don't Want to lose the declaration Line or the string text at the end of the file
try this piece of code:
string line = "";
string[] stringsperate = new string[] { "</cProgram>" };
using (StreamReader sr = new StreamReader("C://blah.xml"))
{
line = sr.ReadToEnd();
Console.WriteLine(line);
}
string text = line.Split(stringsperate, StringSplitOptions.None)[0];
text += "</cProgram>";
XmlDocument xd = new XmlDocument();
xd.LoadXml(text);
Console.Read();
Hope this helps
XDocument.Save() should persist the XML declaration line if the declaration exists initially. I also checked with your XML and the declaration line saved as expected :
var xml = #"<?xml version=""1.0"" encoding=""utf-16""?>
<cProgram xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" ID=""b0eb0c7e-f4de-4bc7-9e62-7a086a8c2fn8"" Version=""16.01"" xmlns=""cProgram"">
<Serie>N </Serie>
<No>123456</No>
<type>101</type>
<Dataset4>larg data here 2 million char</Dataset4>
</cProgram>";
var doc = XDocument.Parse(xml);
doc.Save("test.xml");
So you can implement your idea to temporarily replacing the last line and get it back after changing the inner text.
Fyi, XDocument's .ToString() method doesn't write XML declaration line, but .Save() method does. Question related to this : How to print <?xml version="1.0"?> using XDocument
allow me to answer my question
when I used doc.Load(filepath); it always give Error cause of the disturbing last Line
and C# use UTF-8 as defaults to work with xml files.But in this question it is UTF-16
So I found a very short way to do this & replace innertext with string as I want
string text = File.ReadAllText(filepath);
text = text.Replace("<Serie>N", "<Serie>"+textBox1.Text);
text = text.Replace("<Nom>487382","<Nom>"+textBox2.Text);
//saving file with UTF-16
File.WriteAllText("new.xml", text , Encoding.Unicode);
Question related to this [blog]: How to save this string into XML file? "it is much more answer related than being Question related"

Displaying random XML file in DataGrid

I have been following this article to read an XML file into a datagridview control.
I am posting the relevant piece of code here.
string filePath = "Complete path where you saved the XML file";
dsAuthors.ReadXml(filePath);
dataGrid1.DataSource = dsAuthors;
dataGrid1.DataMember = "authors";
dataGrid1.CaptionText = dataGrid1.DataMember;
Now I want to be able to read any XML file without knowing the elements of the XML file, but the above method requires me to declare the dataGrid1.DataMember = "authors"; which in case of random XML file, I will not know.
Thanks,
Abijeet.
With a little luck the following property has been filled:
dataGrid1.DataMember = dsAuthors.Tables[0].Tablename;

saving xml output to database

In my project I need to read a csv file and convert it into xml and save the xml to database table. I want to save the xml Output directly to database without saving to a file.
I was able to convert csv to xml, but I am not sure how to save it(without saving to a file)
database directly. Any help is appreciated.
Here is my code
var lines = System.IO.File.ReadAllLines(#"C:\test.csv");
var xml = new XElement("TopElement",
lines.Select(line => new XElement("Item",
line.Split(';')
.Select((column, index) => new XElement("Column" + index, column)))));
// XmlTextReader reader = new XmlTextReader(xml.ToString());
//xml.Save(#"C:\xmloutput.xml); // dont want to save to file.
Do you have column of type "XMl" in database in case you are using SQL Server?
You can check Save XML directly to Database with C#
Maintaining XML in SQL Server:
http://msdn.microsoft.com/en-us/library/bb510480(SQL.105).aspx
C# sample (converting XML to string):
http://social.msdn.microsoft.com/Forums/en-US/vstsdb/thread/d1666d13-dea3-4ce8-a818-6b852a63de4f/
Implementing XML in SQL Server:
http://msdn.microsoft.com/en-us/library/ms189887(SQL.105).aspx
Other links:
http://forums.asp.net/t/1316853.aspx/1

Categories