1

I want to deserialize the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<Jobs>
   <Job>
      <Id>1</id>
      <Description>d1</description>
   </Job>
   <Job>
      <Id>2</id>
      <Description>d2</description>
   </Job>
</Jobs>

So I tried to convert the XML to Json and deserialize the jsonstring:

public class Job
{
    public string Id { private get; set; }
    public string ThirdPartyId => $"third-party-id-{Id}";
    public string Description { get; set; }
}

And this how I try to deserialize:

public List<Job> Deserialize(XDocument xDocument)
{
   string jsonString = JsonConvert.SerializeXNode(xDocument);
   return JsonConvert.DeserializeObject<List<Job>>(jsonString);
}

The above fails, I believe because the json contains "xml" node...

{"?xml":{"@version":"1.0","@encoding":"utf-8"},
"Jobs":{"Job":[{"Id":"1","Description":"D1"}, {"Id":"2","Description":"D2"}]}

Is it possible to remove the xml node from xDocument? Is there a better option for doing this?

1 Answer 1

0

You can use: XElement

var xmlNoRoot = XElement.Parse(youXML);
var jsonStringNoRoot = JsonConvert.SerializeXNode(xml, Newtonsoft.Json.Formatting.None, true);

ref: https://qawithexperts.com/article/c-sharp/converting-json-to-xml-or-xml-to-json-using-c/347

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.