Convert XML to JSON in C# - c#

I have an XML and when converting to JSON, all the values became string as below:
XML:
<root><deviceToEgressLocationDistance>600</deviceToEgressLocationDistance></root>
JSON:
{ "deviceToEgressLocationDistance": "600" }
while it should be
JSON:
{ "deviceToEgressLocationDistance": 600 }
below the code I am using but it converts everything to strings
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
string jsonContent = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);
I have checked the solution in
Serialize Xml to Json using type attribute in c#
but I cannot manually parse every value as the xml file properties are changing every time so the next time it could be
XML:
<root><Location1>500.88</Location1><Location2>650</Location2></root>
The xml could have any structure including nesting properties.
Any ideas?
Update: After converting the XML to JSON, this JSON file is going to be the source to another system and if the JSON file has the wrong types like treating numbers as string or even DateTime as string, the subsystem fail to process the input source. So, I need to preserve the types in XML when converting to JSON

Related

Create xml structure from string.split

I want to create a xml file from a string that looks like this:
"Node_1/Node_2/Node_3|Node_1/Node_4|Node_1/Node_2/Node_5"
the output should be:
<Node_1>
<Node_2>
<Node_3>
</Node_3>
<Node_5>
</Node_5>
</Node_2>
<Node_4>
</Node_4>
</Node_1>
the string should resemble something like a file path and the nodes in the xml should resemble something like folders. The first "Folder" is allways the same (Node_1) to keep it a valid xml.
Edit: I am trying to combine xml files which contain some Data and the "path"
where the data is supposed to be written into one big xml file.
First i want to create the new xml from these "paths" and then write the data into the created nodes.
So i don't have any structure to work with only the string which is created by combing the "paths" out of the xml files and separating them with "|" so i can split the string into each "path".
As your input is not a standard format (at least non I'm aware of), you have to write your own parser.
I suggest you create an object (tree) first from the string:
class Node
{
List<Node> Children {get;set;}
}
Then you can use XmlSerializer to create the XML.
XmlSerializer serializer = XmlSerializer(typeof(Node));
using(TextWriter writer = new StreamWriter(filename))
{
serializer.Serialize(writer, node1);
}
https://msdn.microsoft.com/de-de/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

newtonsoft Serialize XML attributes issues

I am Serializing XML document with the help of json.net..
Some of the XML elements have attributes, so when i use:
JsonConvert.SerializeXNode(xml, Newtonsoft.Json.Formatting.None, true);
The XML element <shipmentIndex Name="items">0</shipmentIndex>
transform to that JSON:
{"shipmentIndex":{"#Name":"items","#text":"0"}
I am sending this JSON to an API that expect something like that:
{"shipmentIndex":0}
How can i send to the API the correct data?
i used the attributes for formatting the JSON according to the API demands.
If your xml variable is of type XElement, you can try to use it's RemoveAttributes method:
var cleanXML = xml;
cleanXML.RemoveAttributes();
JsonConvert.SerializeXNode(cleanXML, Newtonsoft.Json.Formatting.None, true);

Embedd xml in json

I want to embed an xml string in a json string. I am returning this json from a web method and at client side I have to extract the xml string from this json data.
I tried this:
var data= $.parseJSON(jsonResponse);
But as the jsonResponse contains XML data it is becoming an invalid json and becomes unable to parse.
Is there any way to successfully embed xml string in json and extract it ?
EDIT:
Tried encoding xml string :
System.Security.SecurityElement.Escape(xmlString)
and then added it to json string.
Still at client side the json couldn't be parsed
EDIT
tried Ted Johnson's solution and the problem is partially fixed.
Now I could parse the json and extract the other attributes. But on accessing the xml attribute, it says undefined. Also couldn't decode it.
You will need to do the following.
Ensure the XML is encoded to project quote escaping. As the XML will need to be parsed as a string. In c# there is a standard way, URL Encoding using C#
ParseJSON
Access JSON attribute which has the xml encoded as a string and decode it. http://www.w3schools.com/jsref/jsref_decodeuri.asp
Parse the XML ... http://api.jquery.com/jQuery.parseXML/ and save result for use.

How to deserialize javascript objects to XML (not JSON) in C#?

I am using the following code to convert JSON string to XML for processing in C#:
XmlDictionaryReader xdr = JsonReaderWriterFactory.CreateJsonReader(System.Text.Encoding.Unicode.GetBytes(jsonStr), new XmlDictionaryReaderQuotas()); // ### QUOTA MAX WILL FIX THE MISSING CLOSING TAGS?
XElement root = XElement.Load(xdr); // Here I get the exception: The token '"' was expected but found '
I have used it with no problem until I tried to parse JSON with strings not enclosed by double quotes (which by the way, I think is perfectly fine with JSON format)
For example:
{string:"value"}
Can any body tell me how can I serialize JSON in C# so that this kind of simple format particulary wont break the code or generate exceptions?
EDIT:
I think what I am reading is not a JSON object but a javascript object like the following:
What's the difference between Javascript Object and JSON object
So question would be: How to deserialize javascript objects to XML (not JSON) in C#?

C# XML conversion

I have a string containing fully formatted XML data, created using a Perl script.
I now want to convert this string into an actual XML file in C#. Is there anyway to do this?
Thanks,
You can load a string into an in-memory representation, for example, using the LINQ to SQL XDocument type. Loading string can be done using Parse method and saving the document to a file is done using the Save method:
open System.Xml.Linq;
XDocument doc = XDocument.Parse(xmlContent);
doc.Save(fileName);
The question is why would you do that, if you already have correctly formatted XML document?
A good reasons that I can think of are:
To verify that the content is really valid XML
To generate XML with nice indentation and line breaks
If that's not what you need, then you should just write the data to a file (as others suggest).
Could be as simple as
File.WriteAllText(#"C:\Test.xml", "your-xml-string");
or
File.WriteAllText(#"C:\Test.xml", "your-xml-string", Encoding.UTF8);
XmlDocument doc = new XmlDocument();
doc.Load(... your string ...);
doc.Save(... your destination path...);
see also
http://msdn.microsoft.com/fr-fr/library/d5awd922%28v=VS.80%29.aspx

Categories

Resources