我开始使用Json。NET将JSON格式的字符串转换为对象,反之亦然。在Json中我不确定。NET框架,它是可能的转换字符串在JSON到XML格式,反之亦然?


当前回答

我不确定这样的转换有什么意义(是的,很多人这样做,但主要是强迫一个方钉通过圆孔)——有结构阻抗不匹配,转换是有损的。所以我建议不要进行这种格式到格式的转换。

但如果你这样做,首先从json转换到对象,然后从对象转换到xml(反之亦然)。进行直接转换会导致丑陋的输出、信息丢失,或者两者兼而有之。

其他回答

你也可以用.NET Framework做这些转换:

JSON到XML:使用System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML转JSON:使用System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}

是的。使用包含辅助方法的JsonConvert类来实现这个精确的目的:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

这里的文档:使用JSON在JSON和XML之间转换。网

是的,你可以这样做(我这样做),但要注意转换时的一些矛盾,并适当地处理。您不能自动符合所有的接口可能性,并且在控制转换方面有有限的内置支持—许多JSON结构和值不能自动以两种方式转换。请记住,我使用的是Newtonsoft JSON库和MS XML库的默认设置,所以你的里程可能会有所不同:

XML -> json

All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

一个新的更新改变了如何处理null(感谢Jon Story指出):https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

Json -> XML

您需要一个将转换为根XML元素的顶级对象,否则解析器将失败。 您的对象名称不能以数字开头,因为它们不能转换为元素(XML技术上甚至比这更严格),但我可以“逃避”打破一些其他元素命名规则。

请随时提到你注意到的任何其他问题,我已经开发了自己的自定义例程,用于准备和清理字符串,因为我来回转换。你的情况可能需要也可能不需要准备/清理。正如StaxMan提到的,您的情况实际上可能需要您在对象之间进行转换……这可能需要适当的接口和一堆case语句/等等来处理我上面提到的警告。

我确实像大卫·布朗说的那样,但我得到了以下例外。

$exception {"There are multiple root elements. Line , position ."} System.Xml.XmlException

一种解决方案是使用根元素修改XML文件,但这并不总是必要的,对于XML流也可能不可能。我的解决方案如下:

var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\App_Data"));
var directoryInfo = new DirectoryInfo(path);
var fileInfos = directoryInfo.GetFiles("*.xml");

foreach (var fileInfo in fileInfos)
{
    XmlDocument doc = new XmlDocument();
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ConformanceLevel = ConformanceLevel.Fragment;

    using (XmlReader reader = XmlReader.Create(fileInfo.FullName, settings))
    {
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                var node = doc.ReadNode(reader);
                string json = JsonConvert.SerializeXmlNode(node);
            }
        }
    }
}

生成错误的XML示例:

<parent>
    <child>
        Text
    </child>
</parent>
<parent>
    <child>
        <grandchild>
            Text
        </grandchild>
        <grandchild>
            Text
        </grandchild>
    </child>
    <child>
        Text
    </child>
</parent>

我不确定这样的转换有什么意义(是的,很多人这样做,但主要是强迫一个方钉通过圆孔)——有结构阻抗不匹配,转换是有损的。所以我建议不要进行这种格式到格式的转换。

但如果你这样做,首先从json转换到对象,然后从对象转换到xml(反之亦然)。进行直接转换会导致丑陋的输出、信息丢失,或者两者兼而有之。