user0000001
user0000001

Reputation: 2233

Define attribute and value for standard key-value pair in JSON using JsonConvert.SerializeXmlNode

I understand this is working as intended but I am trying to simplify and reduce my output from the SerializeXmlNode.

Code:

XmlDocument XMLDoc = new XmlDocument();
XMLDoc.LoadXml(NewXML);

string EventDataJSON = JsonConvert.SerializeXmlNode(XMLDoc, 0, true); 

Here is my XML:

<DataEntries>
    <Data Name="Direction">in</Data> 
    <Data Name="SourceAddress">222.0.0.252</Data> 
    <Data Name="SourcePort">5355</Data> 
    <Data Name="DestAddress">192.168.1.24</Data> 
</DataEntries>

Current JSON output:

{"@Name":"Direction","#text":"in"},
{"@Name":"SourceAddress","#text":"222.0.0.252"},
{"@Name":"SourcePort","#text":"5355"},
{"@Name":"DestAddress","#text":"192.168.1.24"}

Desired JSON output (indention is irrelevant):

{
    "Direction":"in",
    "SourceAddress":"222.0.0.252",
    "SourcePort":"5355",
    "DestAddress":"192.168.1.24"
}

I'd prefer not to use regular expression if I don't have to but really I'm open to anything at this point. My other option is to use JavaScriptSerializer but if there is a way to do this within JSON.net library, that would be preferred.

Upvotes: 0

Views: 136

Answers (1)

dbc
dbc

Reputation: 116981

As stated in Converting between JSON and XML, If the XML created from JSON doesn't match what you want, then you will need to convert it manually. In this case, since you are loading your XML into an XmlDocument beforehand, it seems easiest to pre-process the XML like so:

XmlDocument XMLDoc = new XmlDocument();
XMLDoc.LoadXml(NewXML);

foreach (XmlElement entry in XMLDoc.SelectNodes("//DataEntries"))
{
    var data = entry.ChildNodes.OfType<XmlElement>().ToList();
    foreach (var d in data)
    {
        var e = XMLDoc.CreateElement(d.Attributes["Name"].Value);
        e.InnerText = d.InnerText;
        entry.AppendChild(e);
    }
    foreach (var d in data)
    {
        entry.RemoveChild(d);
    }
}

string EventDataJSON = JsonConvert.SerializeXmlNode(XMLDoc, 0, true);

You might consider switching to the more modern LINQ to XML API. If so, your code would look like:

var doc = XDocument.Parse(NewXML);
foreach (var entry in doc.Descendants("DataEntries"))
{
    var data = entry.Elements("Data").ToList();
    foreach (var d in data)
    {
        entry.Add(new XElement((string)d.Attribute("Name"), d.Value));
    }
    data.Remove();
}

string EventDataJSON = JsonConvert.SerializeXNode(doc, 0, true);

Sample fiddle.

Upvotes: 1

Related Questions