我有一个像这样的json字符串
"{
"RSS": {
"Channel": {
"item": [
{
"title": "Overlay HD/CC",
"guid": "1",
"description": "This example shows tooltip overlays for captions and quality.",
"jwplayer:image": "http://content.jwplatform.com/thumbs/3XnJSIm4-640.jpg",
"jwplayer:source": [
{
"@file": "http://content.jwplatform.com/videos/3XnJSIm4-DZ7jSYgM.mp4",
"@label": "720p"
},
{
"@file": "http://content.jwplatform.com/videos/3XnJSIm4-kNspJqnJ.mp4",
"@label": "360p"
},
{
"@file": "http://content.jwplatform.com/videos/3XnJSIm4-injeKYZS.mp4",
"@label": "180p"
}
],
"jwplayer:track": [
{
"@file": "http://content.jwplatform.com/captions/2UEDrDhv.txt",
"@label": "English"
},
{
"@file": "http://content.jwplatform.com/captions/6aaGiPcs.txt",
"@label": "Japanese"
},
{
"@file": "http://content.jwplatform.com/captions/2nxzdRca.txt",
"@label": "Russian"
},
{
"@file": "http://content.jwplatform.com/captions/BMjSl0KC.txt",
"@label": "Spanish"
}
]
}
]
},
"@xmlns:jwplayer": "http://support.jwplayer.com/customer/portal/articles/1403635-media-format-reference#feeds",
"@version": "2.0"
}
}"
我尝试使用json.net将其转换为xmlDocument:
XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode(json);
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter); // Exception: Cannot use a prefix with an empty namespace.
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}
但是当我尝试访问OuterXml属性时,它会抛出异常“不能使用带有空命名空间的前缀。”
是否有修复该异常或其他方法将json转换为xml字符串? xml字符串的名称空间如下所示
<jwplayer:image>http://content.jwplatform.com/thumbs/3XnJSIm4-640.jpg</jwplayer:image>
答案 0 :(得分:1)
我不确定为什么你的代码抛出异常,因为它必须是一个有效的XML,因为XML已成功加载到XmlDocument
对象。
我可以想到获取格式化XML字符串的另一种方法是使用从XmlDocument.OuterXml
加载未格式化的XML字符串到XDocument
,然后将其转换为格式化的XML字符串:
XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode(json);
XDocument xDoc = XDocument.Parse(xmlDoc.OuterXml);
return xDoc.ToString();
效率不高,但这种方法很简单且有效。