Search code examples
c#asp.netjsonxmlwcf

C# - How to convert complex json to XML with name and value property to tags


Trying convert json to XML with JsonConvert.DeserializeXmlNode(Json.ToString()) and its works but not expected,

First Exapmle:

JSON :

"Emailid": ""

Converted XML :

<Emailid></Emailid>

First example working as expected

Second Example:

JSON :

"ProposalDate": { "Name": "Proposal Date", "Value": "06/05/2019" }

Converted XML :

<ProposalDate>
    <Name>Proposal Date</Name>
    <Value>06/05/2019</Value>
</ProposalDate>

Expected XML for second example:

<ProposalDate Name="Proposal Date" Value="06/05/2019" />

but for second example want ProposalDate tag with Name and Value property. What should i do ?


Solution

  • You could deserialize JSON to a class first, apply [XmlAttribute] to the class properties and then serialize the class to XML. See the XmlAttributeAttribute Class documentation.

    Your class would look something like this:

    public class ProposalDate
    {
        [XmlAttribute]
        public string Name { get; set; }
        [XmlAttribute]
        public string Value { get; set; }
    }
    
    

    Deserializing JSON to object and serializing object to XML are well documented, and examples easily found.