XML to JSON conversion accessing member in C# - c#

I have an XML string like
<Segment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Air">
<carrier />
...
</Segment>
I use JSON.NET to convert that to JSON and the end result has the following members
#xmlns:xsi: "http://www.w3.org/2001/XMLSchema-instance"
#xsi:type: "Air"
carrier
At client end, how do I access the type "Air"? Segment.#xsi:type obviously is illegal.

I presume you use Json.Net at client end.
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xstr);
string jsonText = JsonConvert.SerializeXmlNode(xDoc);
JObject jObj = (JObject)JsonConvert.DeserializeObject(jsonText);
string air = jObj["Segment"]["#xsi:type"].ToString();
//or
dynamic jObj = JsonConvert.DeserializeObject(jsonText);
string air = jObj.Segment["#xsi:type"];

Related

Extract Inner Nodes from XML string to a JSON string

string inputxml = "<transaction>
<node1>value1</node1>
<node2>value2</node2>
<node3>value3</node3>
</transaction>"
I want to convert this XML string to JSON string in the below format after omitting the outermost node:
{"node1";"value1","node2":"value2","node3":"value3"}
You can use :
1 - XDocument to build anonymous object that match the Json like :
string inputxml = #"<transaction>
<node1>value1</node1>
<node2>value2</node2>
<node3>value3</node3>
</transaction>";
var node = XDocument.Parse(inputxml)
.Descendants("transaction")
.Select(x => new
{
Node1 = x.Element("node1").Value,
Node2 = x.Element("node2").Value,
Node3 = x.Element("node3").Value
}).FirstOrDefault();
2 - Newtonsoft to serialize the object like :
string json = JsonConvert.SerializeObject(node);
Demo
Console.WriteLine(json);
Result
{"Node1":"value1","Node2":"value2","Node3":"value3"}
I hope you find this helpful.
As far as i understood your problem you do not have model neither for source XML nor for JSON and names can chenge in future, so we shouldn't use strict names. So we will try to build it dynamically. Pay attention - u'll need to use Newtonsoft.Json nuget pack.
string inputxml = #"<transaction>
<node1>value1</node1>
<node2>value2</node2>
<node3>value3</node3>
</transaction>";
XDocument xdoc = XDocument.Parse(inputxml); //parse XML document
var jprops = xdoc.Root.Elements() // take elements in root of the doc
.Select(x => (x.Name, x.Value)) // map it to tuples (XName, string)
.Select(x => new JProperty(x.Name.LocalName, x.Value)); //map it to enumerbale of Json properties
JObject resultingObj = new JObject(jprops); // construct your json and populate its contents
Console.WriteLine(resultingObj.ToString()); // Write out - u r awesome

How get JSON string from XML string using C#?

I am trying to convert XML string to C# object, I have json string acle in xml tag, as shown below,
<message> <data:gcm xmlns:data=\"google:mobile:data\">{\"message_type\":\"ack\",\"from\":\"sdhad4asd4a-sdasd45ds\",\"message_id\":\"-something\"}</data:gcm> </message>
I want json string from data tag I just want this string from above xml,
{\"message_type\":\"ack\",\"from\":\"sdhad4asd4a-sdasd45ds\",\"message_id\":\"-something\"}
So how can I get this using c#.?
Thank you in advance.
By reading some LINQ to XML documents I got the solution which is like below,
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(msg.ToString());
var result = xdoc.Element("message").Descendants();
var myString = result.FirstOrDefault().Value; //This will out given json string
Again Thank you #JonSkeet for your suggestion.!

XML to BSON using C#

I want to convert a XML file to BSON. then import the BSON to MongoDB. I searched but could not find how to covert this using C#. please provide me a source code to do this using C#
Had the same Problem today.
It's for sure not the best solution, but
i solved it this way in my project and it works for what i need it:
Deserialize XML to Json
Deserialize Json to Bson
using (var reader = new StreamReader(context.Request.Body))
{
var body = reader.ReadToEnd(); // read input string
XmlDocument doc = new XmlDocument();
doc.LoadXml(body); // String to XML Document
string jsonText = JsonConvert.SerializeXmlNode(doc); //XML to Json
var bsdocument = BsonSerializer.Deserialize<BsonDocument>(jsonText); //Deserialize JSON String to BSon Document
var mcollection = Program._database.GetCollection<BsonDocument>("test_collection_05");
await mcollection.InsertOneAsync(bsdocument); //Insert into mongoDB
}

how to exclude null from JSON? (after converting from XML)

Below is code to convert xml to json using http://json.codeplex.com/
how to exclude null from JSON? (ie "SessionId": "null")
string xml = ""; //see XML value below
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc); //See Json value below
Xml Input
<MyResponse>
<Timestamp>2012-01-07T12:43:29</Timestamp>
<SessionId></SessionId>
</MyResponse>
Json Output
{"MyResponse":{"Timestamp":"2012-01-07T12:43:29","SessionId":null}}
You could have a simple string replace since you are outputting the JSON as a string. Do something like this:
jsonText = jsonText.Replace("null", "\"\"");
That should replace every occurrence of null with "".
It is not giving null property like this. It gives like nil to true as attribute in xml element.

JSON.NET XML to String

string json = "{"Animal":{"id":"123","verified":true}}"
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
returnXml = doc.ToString();
Why does "ReturnXml" return the following text "System.Xml.XmlDocument" and not the XML output in string format?
http://json.codeplex.com/
To print XML, you need to use InnerXml
doc.InnerXml;
The ToString method of XmlDocument is not set to output a pretty version of the xml contained therein.
You're best bet may be to just convert that XmlDocument to an XDocument, since that supports a ToString method that outputs actual XML:
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
XDocument linqXML = XDocument.Load(new XmlNodeReader(doc));
returnXML = linqXML.ToString();

Categories

Resources