微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

XML转换成json

方式一:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

public class XMLToJson {

	public static void main(String[] args) throws IOException {
		// Todo Auto-generated method stub
		String xml = readxml();
		System.out.println(xml);
		XMLSerializer xmlSerializer = new XMLSerializer();
		//deal with the special field "type"
		xmlSerializer.setTypeHintsCompatibility(false);
		xmlSerializer.setTypeHintsEnabled(false);
//		xmlSerializer.setSkipNamespaces(true);
//		xmlSerializer.setSkipwhitespace(true);
		JSON json = xmlSerializer.read(xml);
		System.out.println(json.toString());
//		JsonAnalysis josnAnalysis = new JsonAnalysis(json.toString());
//		josnAnalysis.retrieveJson();
	}

	// read xml file
	private static String readxml() throws IOException {
		String path = "C:\\Users\\hitler\\Desktop\\datatype\\bioproject_result.xml";
		FileInputStream fileInputStream = new FileInputStream(path);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				fileInputStream));
		String xml = "";
		String line;
		while ((line = reader.readLine()) != null) {
			xml = xml + line;
		}
		reader.close();
		return xml;
	}
}

使用net.sf.json.xml.XMLSerializer解析的时候,会出现以下几个问题:

(1)当元素的属性中有"type"的时候,XMLSerializer认是不解析的,如果想要程序对这个属性进行解析的话,需要添加以下代码

		xmlSerializer.setTypeHintsCompatibility(false);
		xmlSerializer.setTypeHintsEnabled(false);


(2)当元素节点没有属性的时候,XMLSerilizer就不会对其进行解析,具体解决办法参照【方式二】


方式二:

采用github上面的一个解析工具进行解析;

Mavendependency:

    <dependency>
        <groupId>de.odysseus.staxon</groupId>
        <artifactId>staxon</artifactId>
        <version>1.3</version>
    </dependency>

    <!-- or,to use the Jackson streaming backend -->
    <dependency>
        <groupId>de.odysseus.staxon</groupId>
        <artifactId>staxon-jackson</artifactId>
        <version>1.3</version>
    </dependency>

具体应用代码

示例一:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stax.StAXSource;

import de.odysseus.staxon.json.jsonxMLConfig;
import de.odysseus.staxon.json.jsonxMLConfigBuilder;
import de.odysseus.staxon.json.jsonxMLOutputFactory;

public class XmlToJsonStaxon {
	/**
	 * copy/format XML as JSON using
	 * {@link Transformer#transform(Source,Result)}.
	 * 
	 * @param args
	 *            ignored
	 * @throws TransformerException
	 * @throws XMLStreamException
	 */
	public static void main(String[] args) throws TransformerException,XMLStreamException,IOException {
		InputStream input = XmlToJsonStaxon.class
				.getResourceAsstream("input.xml");
		OutputStream output = System.out;
		/*
		 * If we want to insert JSON array boundaries for multiple elements,we
		 * need to set the <code>autoArray</code> property. If our XML source
		 * was decorated with <code><?xml-multiple?></code> processing
		 * instructions,we'd set the <code>multiplePI</code> property instead.
		 * With the <code>autoprimitive</code> property set,element text gets
		 * automatically converted to JSON primitives (number,boolean,null).
		 */
		jsonxMLConfig config = new jsonxMLConfigBuilder().autoArray(false)
				.autoprimitive(true).prettyPrint(true).build();
		try {
			/*
			 * Create source (XML).
			 */
			XMLStreamReader reader = XMLInputFactory.newInstance()
					.createXMLStreamReader(input);
			Source source = new StAXSource(reader);

			/*
			 * Create result (JSON).
			 */
			XMLStreamWriter writer = new jsonxMLOutputFactory(config)
					.createXMLStreamWriter(output);
			Result result = new StAXResult(writer);

			/*
			 * copy source to result via "identity transform".
			 */
			TransformerFactory.newInstance().newTransformer()
					.transform(source,result);

			System.out.println();
			/*
			 * JsonAnalysis josnAnalysis = new JsonAnalysis((JSON) System.out);
			 * josnAnalysis.retrieveJson();
			 */
		} finally {
			/*
			 * As per StAX specification,XMLStreamReader/Writer.close() doesn't
			 * close the underlying stream.
			 */
			output.close();
			input.close();
		}
	}
}
示例二:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;

import de.odysseus.staxon.json.jsonxMLConfig;
import de.odysseus.staxon.json.jsonxMLConfigBuilder;
import de.odysseus.staxon.json.jsonxMLOutputFactory;

public class StaxonUtils {

	public static void main(String[] args) throws IOException {
		String xml = readxml();
		String json = xml2json(xml);
		System.out.println(json);
		JsonAnalysis josnAnalysis = new JsonAnalysis(json);
		josnAnalysis.retrieveJson();
	}

	// read xml file
	private static String readxml() throws IOException {
		String path = "C:\\Users\\hitler\\Desktop\\datatype\\bioproject_result_neww.xml";
		FileInputStream fileInputStream = new FileInputStream(path);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				fileInputStream));
		String xml = "";
		String line;
		while ((line = reader.readLine()) != null) {
			xml = xml + line;
		}
		reader.close();
		return xml;
	}

	// convert xml to json
	public static String xml2json(String xml) {
		StringReader input = new StringReader(xml);
		StringWriter output = new StringWriter();
		jsonxMLConfig config = new jsonxMLConfigBuilder().autoArray(false)
				.autoprimitive(true).prettyPrint(true).build();
		try {
			XMLEventReader reader = XMLInputFactory.newInstance()
					.createXMLEventReader(input);
			XMLEventWriter writer = new jsonxMLOutputFactory(config)
					.createXMLEventWriter(output);
			writer.add(reader);
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printstacktrace();
		} finally {
			try {
				output.close();
				input.close();
			} catch (IOException e) {
				e.printstacktrace();
			}
		}
		return output.toString();
	}

}

原文地址:https://www.jb51.cc/xml/295909.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。