3

I have a json like below

{
    "Title": null,
    "ProjectName": {
        "@Label": "Project Name",
        "Value": "Test Project Name",
        "@Template": ""
    },
    "ModelNo": {
        "@Label": "Model",
        "Value": "Test Model Number",
        "@Template": ""
    }    
}

I want to convert it to xml like below:

<Root>
    <Title>Test Title</Title>
    <ProjectName Label="Project Name" Template="">Test Project Name</ProjectName>
    <ModelNo Label="Model" Template="">Test Model Number</ModelNo>
</Root>

At present, I used something by JsonConvert.DeserializeXmlNode(Json.ToString()) and add XmlAttribute, the result will be

<Root>
    <Title>Test Title</Title>
    <ProjectName Label="Project Name" Template=""><Value>Test Project Name</Value></ProjectName>
    <ModelNo Label="Model" Template=""><Value>Test Model Number</Value></ModelNo>
</Root>

How to make sure there is no Value, and map Value to xml text

2
  • 1
    According to the docs it seems like you could try renaming the Value property to #text in your JSON. Commented Apr 8, 2024 at 10:31
  • 1
    Where do these xml texts come from? Commented Apr 8, 2024 at 10:39

1 Answer 1

4

You can replace/build a new JSON via LINQ to JSON API. For example (assuming the source values are in the JSON, otherwise analyze and manipulate the jp.Value):

var js = """
         {
             "Title": "Test Title",
             "ProjectName": {
                 "@Label": "Project Name",
                 "Value": "Test Project Name",
                 "@Template": ""
             },
             "ModelNo": {
                 "@Label": "Model",
                 "Value": "Test Model",
                 "@Template": ""
             }
         }
         """;
var jObject = JObject.Parse(js);
var jsonProperties = jObject.Descendants()
    .OfType<JProperty>()
    .Where(jp => jp.Name == "Value")
    .ToList();
foreach (JProperty jp in jsonProperties)
{
  // replace "Value" with "#text" property name 
  jp.Replace(new JProperty("#text", jp.Value)); 
}

var deserializeXmlNode = JsonConvert.DeserializeXmlNode(jObject.ToString(), "Root");

Console.WriteLine(deserializeXmlNode.OuterXml);

Result (formatted):

<Root>
    <Title>Test Title</Title>
    <ProjectName Label="Project Name" Template="">Test Project Name</ProjectName>
    <ModelNo Label="Model" Template="">Test Model</ModelNo>
</Root>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.