Norbert Norbertson
Norbert Norbertson

Reputation: 2210

Json data remove unwanted elements

I have the following in some json I have converted from XML:

"ForSaleStatus":{"items":{"item":{"label":"Not For Sale","value":"2"}}}

This was some xml an application generated from a dropdown. I want to convert it to this in C#:

"ForSaleStatus":"2"

Here is the code I have so far:

var xml = i;
var root = XElement.Parse(xml);

// remove ALL empty elements such as <items/>
root.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();

// convert the node to JSON for easier processing
var json = JsonConvert.SerializeXNode(root);

Can anyone think of a way of converting the json or am I better off going back to the XML and working on that?

The XML looks like this:

<ForSaleStatus>
  <items>
    <item>
       <label>Not For Sale</label>
       <value>2</value>
    </item>
  </items>
</ForSaleStatus>

Upvotes: 1

Views: 1298

Answers (1)

Xiaoy312
Xiaoy312

Reputation: 14477

It would be easier to extract the values you want and just construct the json from that :

var json = JsonConvert.SerializeObject(new Dictionary<string, string>
{
    [root.Name.ToString()] = root.XPathSelectElement("items/item/value").Value
});

If that doesn't compile for you, use this older syntax :

var json = JsonConvert.SerializeObject(new Dictionary<string, string>
{
    { root.Name.ToString(), root.XPathSelectElement("items/item/value").Value }
});

Edit: in case you need values from all the items :

var json = JsonConvert.SerializeObject(root
    .XPathSelectElements("items/item")
    .ToDictionary(
        x => x.XPathSelectElement("label").Value,
        x => x.XPathSelectElement("value").Value
    ));

Upvotes: 1

Related Questions