If you want to purely rely on Json.Net then you can do that as well:
var docInXml = XDocument.Parse("...");
var docInJson = JsonConvert.SerializeXNode(docInXml);
var semiParsedJson = JObject.Parse(docInJson);
var propertyCollection = semiParsedJson["properties"]["property"] as JArray;
var keyValueMapping = new Dictionary<string, string>();
foreach(var item in propertyCollection.Children())
{
keyValueMapping.Add((string)item["@key"], (string)item["#text"]);
}
var result = new JObject(new JProperty("properties", JObject.FromObject(keyValueMapping)));
Let's see the code line-by-line:
var docInXml = XDocument.Parse("...");
- It parses the xml string as
XDocument
var docInJson = JsonConvert.SerializeXNode(docInXml);
- It serializes the
XDocument to json
{
"properties":{
"property":[
{
"@key":"EventId",
"#text":"3300"
},
{
"@key":"source",
"#text":"car"
},
{
"@key":"type",
"#text":"omega"
},
{
"@key":"a341414",
"#text":"any value"
},
{
"@key":"arandomstring_each_time_different",
"#text":"any value"
}
]
}
}
var semiParsedJson = JObject.Parse(docInJson);
- It semi parses the json to be able to perform node traversal
var propertyCollection = semiParsedJson["properties"]["property"] as JArray;
- It retrieves the
property collection as an array
var keyValueMapping = new Dictionary<string, string>();
- It defines a temporary storage for the key attributes and text values
foreach(var item in propertyCollection.Children())
- It iterates through the array's items
keyValueMapping.Add((string)item["@key"], (string)item["#text"]);
- It retrieves the desired fields and converts them from
JObject to string
- It stores them in the intermediate storage
JObject.FromObject(keyValueMapping)))
- It converts the
Dictionary into a JObject
{
"EventId": "3300",
"source": "car",
"type": "omega",
"a341414": "any value",
"arandomstring_each_time_different": "any value"
}
var result = new JObject(new JProperty("properties", ...));
- Finally, it creates a wrapper around the above created
JObject
{
"properties": {
"EventId": "3300",
"source": "car",
"type": "omega",
"a341414": "any value",
"arandomstring_each_time_different": "any value"
}
}
<property>nodes have an attribute, the value is in a#textproperty. But why use Json.NET to convert fromXElementtoExpandoObject? Why not do it directly like so? dotnetfiddle.net/JzCbWd. Is your XML more general than is shown in your question?