Convert XmlDocument to FileInfo - c#

I have a web service which returns a string representing an Xml file. The string is properly formed xml.
I need to create FileInfo object from the string so that I can deserialize it.
I don't have the file path or even if i do thats of no use as it is a disconnected server.
I can convert string to XmlDocument by -
XmlDocument doc = new XmlDocument();
doc.LoadXml(MyString);
How do I get FileInfo so that I can deserialize it? Please help.
Solution:
Thanks for your replies. I created XmlReader from the string returned by the service and used XmlSerializer.Deserialize to get the object I needed.
using (XmlReader tr = XmlReader.Create(new StringReader(mystring)))
{
XmlSerializer serializer = new XmlSerializer(typeof(<T>), extraTypes);
<T> serizalizedForm = serializer.Deserialize(tr) as <T>;
}

you need a class that represents the structure of the xml to deserialize it into. using xsd.exe and an instance of the xml that is returned you can create this class ( /c switch) and then use xmlserializer to deserialize.
Here is an example of a method that deserializes the xml (Update: This link is broken)

Related

XML document got already a DocumentElement node when i try to load XMLReader object into XMLDocument

I want to create in an app - coded with C# - a copy of the actual element of a XMLReader object by using a XMLDocument instance.
The purpose is to get a copy of the actual reader element, so i can read the inner XML from the actual XML element without moving in the original reader.
When i try to load the reader into the XMLDocument i get the error "The document already has a 'DocumentElement' node.".
Any help would be appreciated.
XmlDocument xmlDocument = new XmlDocument();
MemoryStream streamFromReader = new MemoryStream();
xmlDocument.Load(reader); //Here i get the error
xmlDocument.Save(streamFromReader);
streamFromReader.Position = 0;
XmlReader copyReader = XmlReader.Create(streamFromReader);
sb.Append(copyReader.ReadInnerXml());
copyReader.Close();
The problem is that the reader is already positioned somewhere in the middle of the XML file, e.g.:
<Parent> <---- Position of the reader
<Child></Child>
<Child></Child>
</Parent>
<Parent>
<Child></Child>
<Child></Child>
</Parent>
The Load method starts to read the current node and also reads the siblings of the node. This leads to an invalid XML structure, because the document can only have one root element. The docs describe this behavior in the remarks section.
As for the original purpose of the code, I understand you want to perform a Peek (check the contents without advancing the reader) on the XmlReader. There are limited options to achieve this because an XmlReader operates forward-only. The answers to this question describe some options on how to read from an XmlReader without advancing it.
The answer of Markus helped me to get to the solution.
When the XMLReader is getting to an element which has subitems, i must get first the actual position within the file using the interface IXmlLineInfo.
IXmlLineInfo lineInfo = (IXmlLineInfo)reader;
int lineNumber = lineInfo.LineNumber;
int linePosition = lineInfo.LinePosition;
Then i create an instance of XmlTextReader, which reads the file to that position.
When the reminded position was arrived, the XmlTextReader contains the element and i can get the inner XML from it.
Stream stream = new MemoryStream(myFile.FileBytes);
XmlTextReader textReader = new XmlTextReader(stream);
while (textReader.LineNumber < lineNumber)
{
textReader.Read();
}
string innerXml = textReader.ReadInnerXml());
textReader.Close();

Parsing a XML response back to JSON

I'm working on project where i have to make an API request. When I post a JSON request to the server I get the following XML as response:
"<response>
\r\n
<data>
\r\n
<status no=\"0\" substatus=\"0\">
Connection succeeded
</status>\r\n
</data>
\r\n
</response>"
I need to convert the response back to JSON. But when I try to parse it i'm getting an error saying
'Unexpected character encountered while parsing value: <. Path '',
line 0, position 0.'
I'm using NewtonSoftJSON for conversion.
This is the code I'm using to convert the XML string back to JSON:
var response = JsonConvert.DeserializeXmlNode(xmlResponse);
How can I achieve this?
I would be highly confused by any webapi that expect JSON as input and return XML as its response. But if that is really what you're looking at then you need to take the approach in Serializing that XML response into either an XmlDocument or the newer XDocument/XNode and then Serialize an instance of one of those into JSON.
The XmlDocument type has a Load method that consumes a XmlReader. (it also offers a LoadXml but I wanted to show several options here).
The XDocument type has a Parse method that consumes a string with XML.
Based on your example input you can use two approaches:
var xml = #"<response>
<data>
<status no=""0"" substatus=""0"">
Connection succeeded
</status>
</data>
</response>";
// xmldocument
var xmlReader = XmlReader.Create(new StringReader(xml));
var doc = new XmlDocument();
doc.Load(xmlReader);
var response = JsonConvert.SerializeXmlNode(doc);
response.Dump("XMLDoc to Json "); // LINQPad output
// or XDOcument
response = JsonConvert.SerializeXNode(XDocument.Parse(xml));
response.Dump("XDocument to Json");// LINQPad output
And this will be the result:
There is no direct conversion from XML to JSON. And you should be using a XML parser for this response.
Parsing XML (C#) :
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/parsing-xml
I also suggest reading a little bit more about serialization, since this question actually makes no sense.
I have figured out the issue. rene's answer helped to figure out the how to convert from xml to json. But the issue was with my response. I was able to fix it by removing the /" and unwanted double quotes from the response.
response = response.Replace("<response>\"", "<response>")
.Replace("\"<response>", "<response>")
.Replace("\\", "")
.Replace("rn", string.Empty);
var xmlReader = XmlReader.Create(new StringReader(response));
var doc = new XmlDocument();
doc.Load(xmlReader);
var jsonResponse = JsonConvert.SerializeXmlNode(doc);

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.

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.

How to write xml file using C#

I am newer person in c# asp.net .
I want to write xml file in c# code behind file in my asp.net web application and pass this xml file as a string to a webservice . Can any one able to help me its will very useful for my project .
Thank you
As "fiver" had mentioned you could use the XmlDocument or the new simplified version XDocument for creating XML Documents. Here's a sample code snippet from MSDN for creating XML documents and writing to a file.
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
This will write the following text to the xml file
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Child>content</Child>
</Root>
Note: XDocument is supported only on .NET framework 3.5 and above
You can serialize objects in Xml by using XmlSerializer class:
Serializing to a file:
void SaveAsXmlToFile(object o, string fname)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
using (var f = File.Open(fname, FileMode.OpenOrCreate))
ser.Serialize(f, o);
}
You can also use DataContractSerializer class the same way as XmlSerializer.
You can also serialize an object to a string, and return it:
Serializing to a string:
string ToXml(object o)
{
XmlSerializer ser = new XmlSerializer(o.GetType());
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
ser.Serialize(sw, o);
return sb.ToString();
}
Also, if you need more control over produced Xml, you can use structured xml objects, like XmlDocument and so on, or xml writing classes like XmlWriter as denoted in other answers.
You can use the XMLDocument class. It has various CreateXXX methods for creating XML elements.
It seem you don't need to save the XML file, so you can use the Save(String) method to serialize it to a string, when you are done.
See this question:
How can I build XML in C#?
If you're using .Net4 the XDocument class would work, for .Net2 use the XmlDocument.
The XDocument.ToString() directly returns the XML as a string. For the XmlDocument class you would use the XmlDocument.Save() method, to save to a stream or a TextWriter XmlDocument.OuterXml property.
Both examples on that question demonstrate how to output it as a string. You can use that to pass the string to your web service.
using System.Xml;
using System.Xml.Schema;
XmlTextWriter xtwFeed = new XmlTextWriter(Server.MapPath("rss.xml"), Encoding.UTF8);
xtwFeed.WriteStartDocument();
// The mandatory rss tag
xtwFeed.WriteStartElement("rss");
xtwFeed.WriteAttributeString("version", "2.0");
// Write all the tags like above and end all elements
xtwFeed.WriteEndElement();
xtwFeed.WriteEndDocument();
xtwFeed.Flush();
xtwFeed.Close();

Categories