How to read a local xml file into a string - c#

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

Related

How to save a Xml web page content as a XML document in local drive using C# .Net

How to save a below Xml web page content as a XML document in local drive using C# .Net.
URL is as below :
http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote
I want to load few field values into oracle DB table in a daily basis. Please help me to code.
As far as saving the XML as a local file, I have put together the following code.
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote");
System.IO.File.WriteAllText(#"C:\YOUR_FILE_PATH\FILE_NAME.xml", webData);
Just replace YOUR_FILE_PATH and FILE_NAME with where you want to save the data and your desired file name and it should be good.
take a look at XMLDocument class
you can use method Load to load your xml and Save to save it to a file
https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx
First you need to generate the C# classes for your XML.
https://msdn.microsoft.com/en-us/library/hh371548(v=vs.110).aspx
The summary is you copy the xml text and then in a code file but outside of a class, click menu Edit -> Paste Special -> Paste XML as Classes
https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx
Then you can then load the xml file using XmlSerialzer
From there you can use push it to your oracle DB through Entity Framework Connection.
code to deserialize into a list object:
string url = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(list));
HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();
list mylist = (list)xmlSerializer.Deserialize(aResponse.GetResponseStream());
Then you can use mylist as any object.

Save XML file at custom location

I'm a very beginner with c#.
I write a little XML converter. In the debug mode saves my xml files under bin/debug.
I use:
XmlWriter xw = XmlWriter.Create("Filename.xml")
When I compile the code and run it, the xml are not saved.
What can I do to ensure that the xml is stored at a particular path?
The save Location path comes from a form as a string
You just need to combine the path and the xml file name, then use XmlWriter to write xml element:
string pathName = Path.Combine(location, "Filename.xml"); // location is the string from your form.
using (var xw = XmlWriter.Create(pathName))
{
xw.WriteStartElement("myxml");
}
XmlWriter creates a new XmlWriter instance using the filename and XmlWriterSettings object. (Not saving the file!)
When you have the xml you can save it using System.IO:
File.WriteAllText(saveLocationPath, yourXML);

Big Data Xml file (file size over 20GB) convert to Json File

I have an XML file. I want to convert it to JSON with C#. However, the XML file is over 20 GB.
I have tried to read XML with XmlReader, then append every node to a JSON file. I wrote the following code:
var path = #"c:\result.json";
TextWriter tw = new StreamWriter(path, true, Encoding.UTF8);
tw.Write("{\"A\":");
using (XmlTextReader xmlTextReader = new XmlTextReader("c:\\muslum.xml"))
{
while (xmlTextReader.Read())
{
if (xmlTextReader.Name == "A")
{
var xmlDoc = new XmlDocument();
var v = xmlTextReader.ReadInnerXml();
string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None, true);
tw.Write(json);
}
}
}
tw.Write("}");
tw.Close();
This code not working. I am getting error while converting json. Is there any best way to perform the conversion?
I would do it the following way
generate classes out of xsd schema using xsd.exe
open file and read top level ( i e your document level ) tags one by one (with XmlTextReader or XmlReader)
serialize each tag into object using generated classes
deserialize resulting object to json and save to whatever
consider saving in batches of 1000-2000 tags
you are right about serialize/deserialize being slow. still doing work in several threads, preferably using TPL will give you good speed. Also consider using json.net serializer, it is really a lot faster than standard ones ( it is standard for web.api though)
I can put some code snippets in the morning if you need them.
We are processing big ( 1-10gigs) files this manner in order to save data to sql server database.

Convert .txt to .xml

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"));

How do I write an xml document to an asp.net response formatted nicely?

I have xml documents in a database field. The xml documents have no whitespace between the elements (no line feeds, no indenting).
I'd like to output them to the browser, formatted nicely. I would simply like linefeeds in there with some indenting. Is there an easy, preferably built-in way to do this?
I am using ASP.NET 3.5 and C#. This is what I have so far, which is outputting the document all in one line:
I'm about 99.9977% sure I am using the XmlWriter incorrectly. What I am accomplishing now can be done by writing directly to the response. But am I on the right track at least? :)
int id = Convert.ToInt32(Request.QueryString["id"]);
var auditLog = webController.DB.Manager.AuditLog.GetByKey(id);
var xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.OmitXmlDeclaration = true;
var xmlWriter = XmlWriter.Create(Response.OutputStream, xmlWriterSettings);
if (xmlWriter != null)
{
Response.Write("<pre>");
// ObjectChanges is a string property that contains an XML document
xmlWriter.WriteRaw(Server.HtmlEncode(auditLog.ObjectChanges));
xmlWriter.Flush();
Response.Write("</pre>");
}
This is the working code, based on dtb's answer:
int id = Convert.ToInt32(Request.QueryString["id"]);
var auditLog = webController.DB.Manager.AuditLog.GetByKey(id);
var xml = XDocument.Parse(auditLog.ObjectChanges, LoadOptions.None);
Response.Write("<pre>" + Server.HtmlEncode(xml.ToString(SaveOptions.None)) + "</pre>");
Thank you for helping me!
WriteRaw just writes the input unchanged to the underlying stream.
if you want to use built-in formatting, you need first to parse the XML and then convert it back to a string.
The simplest solution is possibly to use XLinq:
var xml = XDocument.Parse(auditLog.ObjectChanges);
Response.Write(Server.HtmlEncode(xml.ToString(SaveOptions.None)));
(This assumes auditLog.ObjectChanges is a string that represents well-formed XML.)
If you need more control over the formatting (indentation, line-breaks) save the XDocument to a MemoryStream-backed XmlWriter, decode the MemoryStream back to a string, and write the string HtmlEncoded.
If auditLog.ObjectChanges is the XML content that needs to be formatted, then you've stored it in an unformatted way. To format it, treat it as XML and write it to an XMLWriter to format it. Then include the formatted XML into the response, with the HTML encoding.

Categories