Reputation: 106
I am converting an XML document to JSON.
I have a node that could be multiple nodes.
The Json.Net documentation says to force the serialization of the node into an array I should add the json:array=true
attribute.
On my root node I add the add the json
namespace:
writer.WriteAttributeString("xmlns", "json", null, "http://james.newtonking.com/json");
then on the element I need to be an array I add the json:array=true
attribute:
writer.WriteAttributeString("Array", "http://james.newtonking.com/json", "true");
The XML looks as expected:
<result xmlns:json="http://james.newtonking.com/json">
<object json:Array="true">
but the JSON looks like this:
"result": {
"@xmlns:json": "http://james.newtonking.com/json",
"object": {
"@json:Array": "true",
What am I doing wrong?
Upvotes: 1
Views: 3276
Reputation: 129777
You've got the XML namespace wrong. It should be:
http://james.newtonking.com/projects/json
not
http://james.newtonking.com/json
Working demo with correct namespace:
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter writer = new XmlTextWriter(sw);
string xmlns = "http://james.newtonking.com/projects/json";
writer.Formatting = System.Xml.Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("result");
writer.WriteAttributeString("xmlns", "json", null, xmlns);
writer.WriteStartElement("object");
writer.WriteAttributeString("Array", xmlns, "true");
writer.WriteStartElement("foo");
writer.WriteString("bar");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
string xml = sb.ToString();
Console.WriteLine(xml);
Console.WriteLine();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc,
Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
}
Output:
<?xml version="1.0" encoding="utf-16"?>
<result xmlns:json="http://james.newtonking.com/projects/json">
<object json:Array="true">
<foo>bar</foo>
</object>
</result>
{
"?xml": {
"@version": "1.0",
"@encoding": "utf-16"
},
"result": {
"object": [
{
"foo": "bar"
}
]
}
}
Upvotes: 2