How to convert JSON to XML or XML to JSON?

后端 未结 13 1099
借酒劲吻你
借酒劲吻你 2020-11-22 05:43

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to X

13条回答
  •  盖世英雄少女心
    2020-11-22 06:19

    I did like David Brown said but I got the following exception.

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

    One solution would be to modify the XML file with a root element but that is not always necessary and for an XML stream it might not be possible either. My solution below:

    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);
                }
            }
        }
    }
    

    Example XML that generates the error:

    
        
            Text
        
    
    
        
            
                Text
            
            
                Text
            
        
        
            Text
        
    
    

提交回复
热议问题