I am trying to create an XML document that closely conforms to a C# object graph and its JSON representation, but am having difficulty with the list representation in the XML. Given this graph
public class X
{
public List<A> Aa { get; set; }
}
public class A
{
public int B;
public bool C;
}
I took the JSON from the above, and tried converting it a couple of ways:
var json = @"{""Aa"":[{""B"":186,""C"":true},{""B"":9,""C"":false},{""B"":182,""C"":true}]}";
var xml = JsonConvert.DeserializeXNode(json, typeof(T).Name, false);
var xml2 = JsonToXml(json);
This produced the following for xml
(no Aa
"container node"):
<X>
<Aa><B>186</B><C>true</C></Aa>
<Aa><B>9</B><C>false</C></Aa>
<Aa><B>182</B><C>true</C></Aa>
</X>
And for xml2
(has "container" node, but some extra noise):
<root type="object">
<Aa type="array">
<item type="object">
<B type="number">186</B>
<C type="boolean">true</C>
</item>
<item type="object">
<B type="number">9</B>
<C type="boolean">false</C>
</item>
<item type="object">
<B type="number">182</B>
<C type="boolean">true</C>
</item>
</Aa>
</root>
The method used to produce the value for xml2
comes from a different approach using the .NET Framework:
XDocument JsonToXml(string jsonString)
{
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(jsonString)))
{
var quotas = new XmlDictionaryReaderQuotas();
return XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(stream, quotas));
}
}
What I want to produce is
<X>
<Aa>
<A><B>186</B><C>true</C></A>
<A><B>9</B><C>false</C></A>
<A><B>182</B><C>true</C></A>
</Aa>
</X>
I have tried changing the writeArrayAttribute
parameter of DeserializeXDocument to true, but that doesn't work either. The documentation for converting between JSON and XML does not help.
How can I produce the compact version that contains the items in a parent Aa
node? Is this going to require some custom deserializer?
The original JSON was created via
var json = JsonConvert.SerializeObject(new X { etc }, Formatting.None, settings);