精华内容
下载资源
问答
  • 一个json格式转xml格式的java实现

    千次阅读 2019-05-05 10:54:14
    源代码如下: ... import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream;...import java.io.FileOutputStream;... JSON2XML tool = new JSON2XML(); tool.run(); } }

    源代码如下:

    package com.test;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import net.sf.json.JSON;
    import net.sf.json.JSONSerializer;
    import net.sf.json.xml.XMLSerializer;
    
    public class JSON2XML 
    {
    	private String mJSONSource;
    	private String mXML;
    	private String mPath = "C:\\Users\\i042416\\Desktop\\1.txt";
    	private String mSavedXML = "C:\\Users\\i042416\\Desktop\\image.xml";
    	private void getSource(String name) throws IOException
    	{
    			File file = new File(mPath);
    			FileInputStream inputStream = new FileInputStream(file);
    			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    			char[] buffer = new char[(int) file.length()];
    			reader.read(buffer, 0, buffer.length);
    			inputStream.close();
    			mJSONSource = new String(buffer);
    			//System.out.println("String length: " + mJSONSource);
    	}
    	
    	public void run() throws IOException
    	{
    		getSource(mPath);
    		parse();
    		saveFile();
    	}
    	private void parse()
    	{
    		 JSON json = JSONSerializer.toJSON(mJSONSource);   
    		 
    		 XMLSerializer xmlSerializer = new XMLSerializer();   
    		 xmlSerializer.setTypeHintsEnabled( false );       
    		 xmlSerializer.setRootName("body" );      
    		 mXML = xmlSerializer.write( json );      
    		 System.out.println(mXML);      
      
    	}
    	
    	private void saveFile()
    	{
    		try
    		{
    			FileOutputStream fos=new FileOutputStream(new File(mSavedXML));
    		    OutputStreamWriter osw=new OutputStreamWriter(fos);
    		    osw.write(mXML);
    		    osw.flush();
    		    osw.close();
    		}
    		catch(Exception ee)
    		{
    		     ee.printStackTrace();
    		}
    	}
    
    	static public void main(String[] argc) throws IOException
    	{
    		JSON2XML tool = new JSON2XML();
    		tool.run();
    	}
    
    }
    
    展开全文
  • XML文件转JSON格式,与JSON转XML文件格式,并写入XML文件 不废话直接上源码 package XmlToJson; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream...

    XML文件转JSON格式,与JSON转XML文件格式,并写入XML文件

    不废话直接上源码

    	package XmlToJson;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.util.Date;
    
    import javax.xml.bind.JAXBException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.stream.XMLEventReader;
    import javax.xml.stream.XMLEventWriter;
    import javax.xml.stream.XMLOutputFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    
    import org.dom4j.DocumentException;
    import org.json.XML;
    import org.w3c.dom.Node;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    
    import de.odysseus.staxon.json.JsonXMLConfig;
    import de.odysseus.staxon.json.JsonXMLConfigBuilder;
    import de.odysseus.staxon.json.JsonXMLInputFactory;
    import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;
    
    public class XmlToJson {
    	
    	/**
    	 * xml 文件 转成json字符串
    	 * @param url
    	 * @return
    	 * @throws IOException
    	 */
    	public static String xmltojson(String url) throws IOException {
    //		InputStream in = XmlToJson.class.getResourceAsStream(url);
    		InputStream in = XmlToJson.class.getClassLoader().getResourceAsStream(url);
    		String xml = IOUtils.toString(in);
    		System.out.println("读取xml文件:"+xml);
    		org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml);
    		System.out.println("xml转json:"+xmlJSONObj.toString());
    		return xmlJSONObj.toString();
    	}
    
    	/*
    	 *json字符串写入xml文件
    	 */
    	public static void jsonWriterxml(String json,String url) throws IOException, JAXBException, DocumentException {
    		String xml = jsontoxml(json);//json字符串转xml格式
    		createXml(url,str2Document(xml));//生成xml文件
    		
    	}
    
    	/*
    	 * json字符串转xml格式
    	 */
    	public static String jsontoxml(String json) {
    		StringReader input = new StringReader(json);
    		StringWriter output = new StringWriter();
    		JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
    		try {
    			XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
    			XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
    			writer = new PrettyXMLEventWriter(writer);
    			writer.add(reader);
    			reader.close();
    			writer.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				output.close();
    				input.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println("json转xml:"+output.toString());
    		return output.toString();
    	}
    
    	/*
    	 * xml格式转Document
    	 */
        public static org.w3c.dom.Document str2Document(String xmlStr) {
            org.w3c.dom.Document doc = null;
            StringReader sr = new StringReader(xmlStr);
            InputSource is = new InputSource(sr);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            try {
                builder = factory.newDocumentBuilder();
                doc =  builder.parse(is);
            } catch (ParserConfigurationException e) {
                System.out.println("ParserConfiguration错误"+e);
            } catch (SAXException e) {
                System.out.println("SAX错误"+e);
            } catch (IOException e) {
                System.out.println("IO错误"+e);
            }
            return doc;
        }
    	
        /*
         * Document写入xml
         */
        public synchronized static void createXml(String fileName, org.w3c.dom.Document document) {
            System.out.println("============进入生成xml方法:" + new Date().toLocaleString() + "=================");
            try {
                // 判断文件是否存在,如存在就删掉它
                File file = new File(fileName);
                if (file.exists()) {
                    file.delete();
                    System.out.println("==============删除xml文件==============");
                }
                /** 将document中的内容写入文件中 */
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                DOMSource source = new DOMSource((Node) document);
                StreamResult result = new StreamResult(new FileOutputStream(fileName));
                transformer.transform(source, result);
                System.out.println("--------------------------------" + "更新 XML文件成功" + "-------------------------------------");
            } catch (final Exception exception) {
                System.out.println("更新" + fileName + "出错:"+exception);
            }
            System.out.println("============退出生成xml方法:" + new Date().toLocaleString() + "=================");
        }
    	
    	
    	
    	
    
    	public static void main(String[] args) throws IOException, JAXBException, DocumentException {
    		String url="score.xml";
    		String str = xmltojson(url);
    		String Nurl= "D:/workspace/akcDemo/src/main/resources/score2.xml" ;
    		jsonWriterxml(str,Nurl);
    	}
    
    }
    
    

    控制台输出如下:

    读取xml文件:<?xml version="1.0" encoding="UTF-8"?>
    <student>
    	<name>Tom</name>
    	<subject>math</subject>
    	<score>80</score>
    </student>
    xml转json:{"student":{"score":80,"subject":"math","name":"Tom"}}
    json转xml:<?xml version="1.0" encoding="UTF-8"?>
    <student>
    	<score>80</score>
    	<subject>math</subject>
    	<name>Tom</name>
    </student>
    
    ============进入生成xml方法:2019-1-25 10:18:56=================
    --------------------------------更新 XML文件成功-------------------------------------
    ============退出生成xml方法:2019-1-25 10:18:56=================
    

    可以在maven的资源目录看到新生成的文件了

    展开全文
  • JSON格式转换成XML格式

    千次阅读 2016-09-13 16:41:47
    JSON格式转换成XML格式 第一种方法: 需要使用命名空间System.Runtime.Serialization.Json 下面有JsonReaderWriterFactory XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader...

    JSON格式转换成XML格式

    第一种方法:

    需要使用命名空间System.Runtime.Serialization.Json

    下面有JsonReaderWriterFactory

    XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max);
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);
     

     

    使用组件:System.Web.Extensions

    类全称:System.Web.Script.Serialization.JavaScriptSerializer

    要先引用 System.Web.Extensions

    需要使用的命名空间   System.Web.Script.Serialization.JavaScriptSerializer

    下面有JavaScriptSerializer

    // json字符串转换为Xml对象
    public static XmlDocument Json2Xml(string sJson)
    {
                //XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(sJson), XmlDictionaryReaderQuotas.Max);
                //XmlDocument doc = new XmlDocument();
                //doc.Load(reader); 

                JavaScriptSerializer oSerializer = new JavaScriptSerializer();
                Dictionary<string, object> Dic = (Dictionary<string, object>)oSerializer.DeserializeObject(sJson);
                XmlDocument doc = new XmlDocument();
                XmlDeclaration xmlDec;
                xmlDec = doc.CreateXmlDeclaration("1.0", "gb2312", "yes");
                doc.InsertBefore(xmlDec, doc.DocumentElement);
                XmlElement nRoot = doc.createElement_x("root");
                doc.AppendChild(nRoot);
                foreach (KeyValuePair<string, object> item in Dic)
               {
                    XmlElement element = doc.createElement_x(item.Key);
                    KeyValue2Xml(element, item);
                    nRoot.AppendChild(element);
               }
                return doc;

    private static void KeyValue2Xml(XmlElement node, KeyValuePair<string, object> Source)
    {
              object kValue = Source.Value;
               if (kValue.GetType() == typeof(Dictionary<string, object>))
              {
                  foreach (KeyValuePair<string, object> item in kValue as Dictionary<string, object>)
                  {
                       XmlElement element = node.OwnerDocument.createElement_x(item.Key);
                       KeyValue2Xml(element, item);
                       node.AppendChild(element);
                  }
              }
              else if (kValue.GetType() == typeof(object[]))
              {
                 object[] o = kValue as object[];
                 for (int i = 0; i < o.Length; i++)
                    {
                         XmlElement xitem = node.OwnerDocument.createElement_x("Item");
                         KeyValuePair<string, object> item = new KeyValuePair<string, object>("Item", o[i]);
                         KeyValue2Xml(xitem, item);
                         node.AppendChild(xitem);
                    }

               }
               else
               {
                    XmlText text = node.OwnerDocument.CreateTextNode(kValue.ToString());
                    node.AppendChild(text);
               }

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.IO;
    using System.Windows.Forms;
    using System.Runtime.Serialization.Json;
    using System.Collections;
    //using Open_Newtonsoft_Json;

    namespace WeChatTool
    {
    public static class xmlHelper
    {
    //XmlTextWriter
    public static void ss()
    {
    String filename = String.Concat("test3.xml");
    using (StreamWriter sw = new StreamWriter(filename))
    {
    // Create Xml Writer. 
    XmlTextWriter xmlWriter = new XmlTextWriter(sw);
    // 也可以使用public XmlTextWriter(string filename, Encoding encoding)来构造 
    // encoding默认为 UTF-8. 
    //XmlTextWriter writer = new XmlTextWriter("test3.xml", null); 
    // Set indenting so that its easier to read XML when open in Notepad and such apps. 
    xmlWriter.Formatting = Formatting.Indented;
    // This will output the XML declaration 
    xmlWriter.WriteStartDocument();
    xmlWriter.WriteStartElement("Contacts");
    xmlWriter.WriteStartElement("Contact");
    xmlWriter.WriteAttributeString("id", "01");
    xmlWriter.WriteElementString("Name", "Daisy Abbey");
    xmlWriter.WriteElementString("Gender", "female");
    // close contact </contact> 
    xmlWriter.WriteEndElement();
    // close contacts </contact> 
    xmlWriter.WriteEndElement();
    xmlWriter.WriteEndDocument();
    xmlWriter.Close();
    }
    }

    //LINQ to XML 的XDocument
    public static void xx()
    {
    //var doc = new XDocument(new XElement("Contacts", 
    // new XElement("Contact", new XAttribute("id", "01"),
    // new XElement("Name", "Daisy Abbey"), 
    // new XElement("Gender", "female"))));
    //doc.Save("test2.xml");
    }

    //XmlDocument 写入
    public static void XmlDocumentWriter(string userName, string appid, string appsecret, DateTime appdate)
    {
    #region MyRegion
    try
    {
    string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
    //if (File.Exists(xmlPath)==false string.IsNullOrEmpty(xmlPath) || xmlPath == "")
    if (File.Exists(xmlPath) == false)
    {
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
    var root = xmlDoc.CreateElement("config");
    xmlDoc.AppendChild(root);
    // User UserInfo
    XmlElement elementUser = xmlDoc.CreateElement("dev");
    //elementUser.InnerText = userName;
    root.AppendChild(elementUser);

    XmlElement elementName = xmlDoc.CreateElement("Name");
    elementName.InnerText = userName;
    elementUser.AppendChild(elementName);

    XmlElement elementAppid = xmlDoc.CreateElement("Appid");
    elementAppid.InnerText = appid;
    //XmlAttribute attrID = xmlDoc.CreateAttribute("id");
    //attrID.Value = "01";
    //elementAppid.Attributes.Append(attrID);
    elementUser.AppendChild(elementAppid);

    XmlElement elementAppsecret = xmlDoc.CreateElement("Appsecret");
    elementAppsecret.InnerText = appsecret;
    elementUser.AppendChild(elementAppsecret);

    //XmlElement elementDate = xmlDoc.CreateElement("AppDate");
    //elementDate.InnerText = appdate.ToLocalTime().ToString();
    //elementUser.AppendChild(elementDate);

    xmlDoc.Save("config.xml");
    MessageBox.Show("用户信息保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
    {
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(xmlPath);
    //XmlNode node = doc.SelectSingleNode("/Users/UserInfo/Name");
    XmlNodeList nodes = xmlDoc.SelectNodes("/config/dev");
    if (nodes.Count > 0)
    {
    // User 
    XmlNode root = xmlDoc.SelectSingleNode("/config");

    XmlElement elementUser = xmlDoc.CreateElement("dev");
    //elementUser.InnerText = userName;
    root.AppendChild(elementUser);

    XmlElement elementName = xmlDoc.CreateElement("Name");
    elementName.InnerText = userName;
    elementUser.AppendChild(elementName);

    XmlElement elementAppid = xmlDoc.CreateElement("Appid");
    elementAppid.InnerText = appid;
    //XmlAttribute attrID = xmlDoc.CreateAttribute("id");
    //attrID.Value = "01";
    //elementAppid.Attributes.Append(attrID);
    elementUser.AppendChild(elementAppid);

    XmlElement elementAppsecret = xmlDoc.CreateElement("Appsecret");
    elementAppsecret.InnerText = appsecret;
    elementUser.AppendChild(elementAppsecret);

    //XmlElement elementDate = xmlDoc.CreateElement("AppDate");
    //elementDate.InnerText = appdate.ToLocalTime().ToString();
    //elementUser.AppendChild(elementDate);

    xmlDoc.Save("config.xml");
    MessageBox.Show("用户信息保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show("用户信息保存有问题! " + ex.ToString(), "提示信息!", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
    //throw;
    }
    #endregion
    }

    //XmlDocument11 读取
    public static Queue XmlDocumentQuery()
    {
    Queue queue = new Queue();
    string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
    if (string.IsNullOrWhiteSpace(xmlPath) || xmlPath == null)
    {
    return queue;
    }
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlPath);
    //根据要查询的字段进行查询,遍历使用的是xpath
    XmlNodeList nodes = doc.SelectNodes("/config/dev");
    foreach (XmlNode xmlnode in nodes)
    {
    if (xmlnode.HasChildNodes)
    {
    if (xmlnode.ChildNodes.Count > 2)
    {
    FrmUser user = new FrmUser();
    user.UserName = xmlnode.ChildNodes[0].InnerText;
    user.Appid = xmlnode.ChildNodes[1].InnerText;
    user.Appsecret = xmlnode.ChildNodes[2].InnerText;
    queue.Enqueue(user);
    }
    else if (xmlnode.ChildNodes.Count > 1)
    {
    FrmUser user = new FrmUser();
    user.UserName = xmlnode.ChildNodes[0].InnerText;
    user.Appid = xmlnode.ChildNodes[1].InnerText;
    //user.Appsecret = xmlnode.ChildNodes[2].InnerText;
    queue.Enqueue(user);
    }
    else if (xmlnode.ChildNodes.Count > 0)
    {
    FrmUser user = new FrmUser();
    user.UserName = xmlnode.ChildNodes[0].InnerText;
    //user.Appid = xmlnode.ChildNodes[1].InnerText;
    //user.Appsecret = xmlnode.ChildNodes[2].InnerText;
    queue.Enqueue(user);
    }
    }
    }
    return queue;
    }

    //XmlDocument 读取
    public static XmlNode XmlDocumentQuery(string userName, string appid, string appsecret, DateTime appdate)
    {
    string xmlPath = System.IO.Path.Combine(Application.StartupPath, "UserInfo.xml");
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlPath);
    //根据要查询的字段进行查询,遍历使用的是xpath
    string xx = userName;
    DateTime xx1 = appdate;
    //XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
    XmlNodeList nodes = doc.SelectNodes("/Users/UserInfo");
    foreach (XmlNode xmlnode in nodes)
    {
    if (xmlnode.HasChildNodes)
    {
    foreach (XmlNode xmlSubNode in xmlnode.ChildNodes)
    {
    if (xmlSubNode.InnerText == xx)
    {
    //this.richTextBox3.AppendText("用户信息:");
    foreach (XmlNode SubNode in xmlnode.ChildNodes)
    {
    return SubNode;
    //this.richTextBox3.AppendText(Environment.NewLine + " " + SubNode.Name + ":" + SubNode.InnerText);
    }
    //return;
    }
    }
    }
    }
    return null;
    }

    //XmlDocument 修改
    public static void XmlDocumentModified(FrmUser oldUser, FrmUser newuUser, DateTime appdate)
    {
    string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlPath);
    //根据要查询的字段进行查询,遍历使用的是xpath
    //XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
    XmlNodeList nodes = doc.SelectNodes("/config/dev");
    foreach (XmlNode xmlnode in nodes)
    {
    if (xmlnode.HasChildNodes)
    {
    if (xmlnode.ChildNodes.Count > 2)
    {
    if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName
    && xmlnode.ChildNodes[1].InnerText == oldUser.Appid
    && xmlnode.ChildNodes[2].InnerText == oldUser.Appsecret)
    {
    xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
    xmlnode.ChildNodes[1].InnerText = newuUser.Appid;
    xmlnode.ChildNodes[2].InnerText = newuUser.Appsecret;
    }
    }
    else if (xmlnode.ChildNodes.Count > 1)
    {
    if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName
    && xmlnode.ChildNodes[1].InnerText == oldUser.Appid)
    {
    xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
    xmlnode.ChildNodes[1].InnerText = newuUser.Appid;
    }
    }
    else if (xmlnode.ChildNodes.Count > 0)
    {
    if (xmlnode.ChildNodes[0].InnerText == oldUser.UserName)
    {
    xmlnode.ChildNodes[0].InnerText = newuUser.UserName;
    }
    }

    }
    }
    doc.Save("config.xml");
    MessageBox.Show("用户信息修改保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    //XmlDocument 删除
    public static void XmlDocumentDelete(FrmUser user, DateTime appdate)
    {
    string xmlPath = System.IO.Path.Combine(Application.StartupPath, "config.xml");
    XmlDocument doc = new XmlDocument();
    doc.Load(xmlPath);
    //根据要查询的字段进行查询,遍历使用的是xpath
    //XmlNode node = doc.SelectSingleNode("/UserInfo/"+comboBox1.SelectedItem);
    XmlNodeList nodes = doc.SelectNodes("/config/dev");
    foreach (XmlNode xmlnode in nodes)
    {
    if (xmlnode.HasChildNodes)
    {
    if (xmlnode.ChildNodes.Count > 2)
    {
    if (xmlnode.ChildNodes[0].InnerText == user.UserName
    && xmlnode.ChildNodes[1].InnerText == user.Appid
    && xmlnode.ChildNodes[2].InnerText == user.Appsecret)
    {
    XmlNode parentNode = xmlnode.ParentNode;
    parentNode.RemoveChild(xmlnode);
    }
    }
    else if (xmlnode.ChildNodes.Count > 1)
    {
    if (xmlnode.ChildNodes[0].InnerText == user.UserName
    && xmlnode.ChildNodes[1].InnerText == user.Appid)
    {
    XmlNode parentNode = xmlnode.ParentNode;
    parentNode.RemoveChild(xmlnode);
    }
    }
    else if (xmlnode.ChildNodes.Count > 0)
    {
    if (xmlnode.ChildNodes[0].InnerText == user.UserName)
    {
    XmlNode parentNode = xmlnode.ParentNode;
    parentNode.RemoveChild(xmlnode);
    }
    }

    }
    }
    doc.Save("config.xml");
    MessageBox.Show("用户信息删除保存成功!", "提示信息!", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }


    public static XmlDocument JsonToXml(string json)
    {
    XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max);
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);
    return doc;
    }
    // 从一个对象信息生成Json串
    public static string ObjectToJson(object obj)
    {
    string json = null;
    //StringBuilder sb = new StringBuilder();
    //JsonSerializer serialize = new JsonSerializer();
    //serialize.Serialize
    DataContractJsonSerializer serialize = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serialize.WriteObject(ms, obj);
    byte[] readbyte = new byte[ms.Length];
    ms.Read(readbyte, 0, (int)ms.Length);
    json = Encoding.UTF8.GetString(readbyte);
    return json;
    }
    // 从一个Json串生成对象信息
    public static object JsonToObject(string jsonString, object obj)
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    return serializer.ReadObject(mStream);
    }

    }
    }

    第二种方法:

    XML TO JSON  

    string xml = @"<?xml version=""1.0"" standalone=""no""?>

    <root>

      <person id=""1"">
      <name>Alan</name>
      <url>http://www.google.com</url>
      </person>
      <person id=""2"">
      <name>Louis</name>
      <url>http://www.yahoo.com</url>
      </person>
    </root>";

     

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    string jsonText = JsonConvert.SerializeXmlNode(doc);
    //{
    //  "?xml": {
    //    "@version": "1.0",
    //    "@standalone": "no"
    //  },
    //  "root": {
    //    "person": [
    //      {
    //        "@id": "1",
    //        "name": "Alan",
    //        "url": "http://www.google.com"
    //      },
    //      {
    //        "@id": "2",
    //        "name": "Louis",
    //        "url": "http://www.yahoo.com"
    //      }
    //    ]
    //  }
    //}  
     
    JSON TO XML   
    string json = @"{
      ""?xml"": {
        ""@version"": ""1.0"",
        ""@standalone"": ""no""
      },
      ""root"": {
        ""person"": [
          {
            ""@id"": ""1"",
            ""name"": ""Alan"",
            ""url"": ""http://www.google.com""
          },
          {
            ""@id"": ""2"",
            ""name"": ""Louis"",
            ""url"": ""http://www.yahoo.com""
          }
        ]
      }
    }";
      
    XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
    // <?xml version="1.0" standalone="no"?>
    // <root>
    //   <person id="1">
    //   <name>Alan</name>
    //   <url>http://www.google.com</url>
    //   </person>
    //   <person id="2">
    //   <name>Louis</name>
    //   <url>http://www.yahoo.com</url>
    //   </person>
    // </root>

      

    DEMO:JSON TO XML 

    string json_str = "{\"a\":\"a\",\"b\":\"b\"}";
    //json 的字符串需要按照这个格式 书写,否则会报错
    string json = @"{
      ""?xml"": {
        ""@version"": ""1.0"",
        ""@standalone"": ""no""
      },
      ""root"":" + json_str + "}"; 
    if (!string.IsNullOrEmpty(json))
    {
        XmlDocument doc = JsonConvert.DeserializeXmlNode(json);     
    }
    这个个方法可以直接使用

    public static XmlDocument JsonToXml(string json)
    {
    XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max);
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);
    return doc;
    }
    // 从一个对象信息生成Json串
    public static string ObjectToJson(object obj)
    {
    string json = null;
    //StringBuilder sb = new StringBuilder();
    //JsonSerializer serialize = new JsonSerializer();
    //serialize.Serialize
    DataContractJsonSerializer serialize = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serialize.WriteObject(ms, obj);
    byte[] readbyte = new byte[ms.Length];
    ms.Read(readbyte, 0, (int)ms.Length);
    json = Encoding.UTF8.GetString(readbyte);
    return json;
    }
    // 从一个Json串生成对象信息
    public static object JsonToObject(string jsonString, object obj)
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    return serializer.ReadObject(mStream);
    }

    展开全文
  • 将 .json 格式 转换成 .xml格式

    千次阅读 热门讨论 2019-08-30 21:30:33
    1. 转换前的 .json 格式文件的内容: json 是一个字典,具体内容看下面这个链接: ...2. 转换后的 .xml 格式文件的内容: <annotation> <folder>VOC2012</folder> # 这些值训练的...

    1. 转换前的 .json 格式文件的内容:

    json 是一个字典,具体内容看下面这个链接:
    https://blog.csdn.net/weixin_42419002/article/details/100159408

    2. 转换后的 .xml 格式文件的内容:

    <annotation>
    	<folder>VOC2012</folder>  #  这些值训练的时候不会被用到
    	<filename>2007_000661.jpg</filename>
    	<source>
    		<database>The VOC2007 Database</database>
    		<annotation>PASCAL VOC2007</annotation>
    		<image>flickr</image>
    	</source>
    	<size>
    		<width>500</width>  # 这个值需要改变
    		<height>375</height>  # 这个值需要改变
    		<depth>3</depth>
    	</size>
    	<segmented>0</segmented>
    	<object>
    		<name>sofa</name>  # 这个值需要改变
    		<pose>Unspecified</pose>
    		<truncated>1</truncated>
    		<difficult>0</difficult>
    		<bndbox>
    			<xmin>119</xmin>  # 这个值需要改变
    			<ymin>177</ymin>  # 这个值需要改变
    			<xmax>331</xmax>  # 这个值需要改变
    			<ymax>278</ymax>  # 这个值需要改变
    		</bndbox>
    	</object>
    	<object>
    		<name>chair</name>  # 这个值需要改变
    		<pose>Unspecified</pose>
    		<truncated>1</truncated>
    		<difficult>0</difficult>
    		<bndbox>
    			<xmin>133</xmin>  # 这个值需要改变
    			<ymin>159</ymin>  # 这个值需要改变
    			<xmax>179</xmax>  # 这个值需要改变
    			<ymax>197</ymax>  # 这个值需要改变
    		</bndbox>
    	</object>
    </annotation>
    

    3. 将 .json 转换成 .xml 格式代码:

    import  os
    import json
    from lxml import etree as ET
    from xml.dom import minidom
    
    def edit_xml(objects, id, dir):
        save_xml_path = os.path.join(dir, "%s.xml" % id)  # xml
    
        root = ET.Element("annotation")
        # root.set("version", "1.0")  
        folder = ET.SubElement(root, "folder")
        folder.text = "none"
        filename = ET.SubElement(root, "filename")
        filename.text = "none"
        source = ET.SubElement(root, "source")
        source.text = "201908"
        owner = ET.SubElement(root, "owner")
        owner.text = "YZN"
        size = ET.SubElement(root, "size")
        width = ET.SubElement(size, "width")
        width.text = str(2048)
        height = ET.SubElement(size, "height")
        height.text = str(2048)
        depth = ET.SubElement(size, "depth")
        depth.text = "3"
        segmented = ET.SubElement(root, "segmented")
        segmented.text = "0"
        for obj in objects:  #  
            object = ET.SubElement(root, "object")
            name = ET.SubElement(object, "name")  # number
            name.text = obj["category"]
            # meaning = ET.SubElement(object, "meaning")  # name
            # meaning.text = inf_value[0]
            pose = ET.SubElement(object, "pose")
            pose.text = "Unspecified"
            truncated = ET.SubElement(object, "truncated")
            truncated.text = "0"
            difficult = ET.SubElement(object, "difficult")
            difficult.text = "0"
            bndbox = ET.SubElement(object, "bndbox")
            xmin = ET.SubElement(bndbox, "xmin")
            xmin.text = str(int(obj["bbox"]["xmin"]))
            ymin = ET.SubElement(bndbox, "ymin")
            ymin.text = str(int(obj["bbox"]["ymin"]))
            xmax = ET.SubElement(bndbox, "xmax")
            xmax.text = str(int(obj["bbox"]["xmax"]))
            ymax = ET.SubElement(bndbox, "ymax")
            ymax.text = str(int(obj["bbox"]["ymax"]))
        tree = ET.ElementTree(root)
        tree.write(save_xml_path, encoding="UTF-8", xml_declaration=True)
        root = ET.parse(save_xml_path) 
        file_lines = minidom.parseString(ET.tostring(root, encoding="Utf-8")).toprettyxml(
            indent="\t") 
        file_line = open(save_xml_path, "w", encoding="utf-8")  
        file_line.write(file_lines)
        file_line.close()
        
    def  getDirId(dir):  # get the  id list  of id.png
        names = os.listdir(dir)
        ids = []
        for name in names:
            # path = os.path.join(dir, name)
            # img  = cv2.imread(path)
            # w, h, c = img.shape
            # if name.endswith(".jpg") or name.endswith(".png"):
                # ids["%s" % name.split(".")[0]] = [w, h, c]
            ids.append(name.split(".")[0])
        return ids  
    
    filedir = "annotations.json"
    annos = json.loads(open(filedir).read())
    
    trainIds =  getDirId("Tinghua100K/images/train/")
    testIds =  getDirId("Tinghua100K/images/test/")
    
    ids = annos["imgs"].keys() #  all img ids in .json 
    
    for id in ids:
    	#  json 中的ID图片有待检测目标,且该id图片在 train文件夹中
        if len(annos["imgs"][id]["objects"]) > 0 and (id in trainIds) and :
            objects = annos["imgs"][id]["objects"]
            edit_xml(objects, id, dir = "xmlLabel/train")
            
        elif len(annos["imgs"][id]["objects"]) > 0 and (id in testIds):
            objects = annos["imgs"][id]["objects"]
            edit_xml(objects, id, dir = "xmlLabel/test")
            
    
    展开全文
  • 结果xml截图 json数据 main启动 import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public static void main(String[] args) { // 本地读取方式 new xxx()....
  • JSON转换成XMLXML转换成JSON

    万次阅读 2016-08-26 17:10:37
    JSON转换成XMLXML转换成JSON
  • json转xmlxml转json

    万次阅读 2018-09-19 17:21:48
    一、jar包 所需jar包 二、xml2json 方法一: ...public String xml2json(String xml) {  //创建XMLSerializer对象  XMLSerializer xmlSerializer = new XMLSerializer();  //将xml转化为json...
  • JSONXML比较
  • C++常用函数 XML JSON格式转换 数据格式在编程里面很常见,不同的系统都会有自己的标准。因为给有各的定义,每次做第三方开发系统对接的时候数据格式标准都是头疼的事情。 在开发过程中比较常见的比如有JsonXML、...
  • c# XML转JSONJSON转XML,object转JSON

    万次阅读 2018-06-04 13:28:05
    public static string XmlTojson(this string s, string r = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>") { s = s.Replace(r, ""); var doc = new XmlDocument(); ...
  • json数据转换为xml格式

    2017-05-10 13:02:08
    result = ServiceUtils.invoke("component:oa-infoPortal/PortalServiceInvoker","getTodoNumForBpm", params);... //json数据转换为xml格式  String str=JSON.toJSONString(result.getResult());  JSONArray
  • js实现xml转jsonjson转xml

    万次阅读 2018-04-12 09:58:45
    &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="...js实现xml转jsonjson转xml&lt;/title&gt; &lt;styl
  • 字符串格式xml转json格式

    千次阅读 2017-08-22 15:16:47
    一、使用org.json中的 XML.toJSONObject...在json格式的字符串之后,可通过阿里的fastjson进行取值,如下: gradle依赖 :compile group: 'org.json', name: 'json', version: '20170516'  compile group:
  • python中将xml格式转json格式

    千次阅读 2017-10-12 22:03:41
    python中将xml格式转json格式
  • xml格式转换为json格式

    千次阅读 2019-03-22 13:13:14
    在Python编程中,经常遇到xml格式的文件或字符串。由于json格式的方便性,常常希望将xml格式转换为json格式来处理,这可以通过模块xmltodict来实现。 xmltodict模块通过pip来下载和安装...
  • json格式数据转换为xml格式

    千次阅读 2016-06-17 21:21:05
    1.json格式:   [{"name":"zhangsan's","sex":"man"},{"name":"lisi","sex":"woman"}] //注意标红处 2.处理: ... //声明xml格式文件  header("content-type: text/xml; charset=utf-8");  //路
  • Json格式对象转换为XML

    千次阅读 2015-07-24 15:24:10
    编制XML的包:org.jdom使用rest接口从前端获取Json格式的对象@Path("Testrest") public class TestRest extends ApiBase { @POST @Path("rest") @Consumes(MediaType.APPLICATION_JSON) public Do
  • 1.JSON格式 随便写了一个,带有json数组,如下: { &amp;quot;TxnBatchNo&amp;quot;: &amp;quot;20170607152322&amp;quot;, &amp;quot;TxnSeq&amp;quot;: &amp;quot;1&amp;quot...
  • 超简单的json转xml,xml转json

    千次阅读 2020-01-11 15:39:02
    System.out.println("xml转json:"+jsonObject); String s = XML.toXml(jsonObject); System.out.println("json转xml:"+s); } } 远行结果 推荐Hutool的API文档里面有很多实用的接口 https://www.hutool.cn/ 例如...
  • python:json转xml

    千次阅读 2019-11-11 10:50:28
    文章目录python读写jsonjsonpython读写xmlpython:json转xmlpython:xml转json python读写json json JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。JSON采用完全独立于...
  • C# json xml 字符串

    千次阅读 2019-03-01 09:21:10
    本文告诉大家如何将 json xml 或将 xml json 字符串
  • python中json文件转xml文件

    千次阅读 2018-02-07 09:45:36
    #!/usr/bin/env python # coding=utf-8 ...from xml.dom.minidom import Document src = open(u"E:\\学习资料\\dump_8530366515657419993.json") obj = json.loads(src.read()) doc = Document() def traver
  • Json转XML

    千次阅读 2018-05-08 09:23:55
    1.第一种方法(1)使用XML.java中提供的XML.toJSONObject(xml)方法即可完成xmljson的转换,同时也可以对JSON进行格式化[java] view plain copy/* 第一种方法,使用JSON-JAVA提供的方法 */ //将xml转为json ...
  • Python中xmljson格式

    千次阅读 2018-07-11 14:17:38
    Python中xml和json格式是可以互转的,就像json格式转Python字典对象那样。xml格式json格式互转用到的xmltodict库安装xmltodict库C:\Users\Administrator&gt;pip3 install xmltodictCollecting xmltodict ...
  • 场景:在使用了mask rcnn跑实验后标注了大量地json格式文件,现在打算使用yolo和faster rcnn 跑实验 所以需要将之前地json文件转为xml  但是找了很久,没发现有批量处理的代码,所以自己写了一个,经测可用。 ...
  • python 下json转xml、html,xml转json

    千次阅读 2019-12-11 11:03:52
    文章目录一、说明:二、简单操作使用:1、json转xml:①、安装:②、代码中的josn③、代码:2、json转html:①、安装:②、代码:3、xml转json:①、安装:②、代码:③、去掉属性:4、html转json(暂时没有解决) ...
  • JS实现xmljson格式的互

    千次阅读 2017-02-08 11:30:51
    jsonxml格式是我们日常开发中的常见需求,如何在前端实现这两种格式的转换呢? 这里需要用到两个js插件:ObjTree.js、jkl-dumper.js 话不多说,直接上示例: json与xml互    xml  json     ...
  • 多层json转xml

    千次阅读 2017-08-12 15:35:55
    实际开发中我们遇到的json很多时候都是多层结构的json,这个时候我们该如何实现多层结构转xml呢?(大多数是在做金融项目时候遇到,变化部分可以采用如下方式) 代码如下: import java.util.Iterator; import ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 404,316
精华内容 161,726
关键字:

json格式转xml