方式一:
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(); } }