java XML processing tools

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.StringReader;

import java.io.UnsupportedEncodingException;

 

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.XMLWriter;

import org.xml.sax.InputSource;

import org.xml.sax.SAXException;

 

import net.sf.json.JSONObject;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

 

import oracle.net.aso.p;

 

public class XmlUtil {

/**

 *

 * @param document

 * @Param path   indicates the path and file name

 * @Param flag   whether escape

 */

public static void writeXML(Document root,String path,boolean flag) {

OutputFormat format = new OutputFormat("    ",flag);  

  format.setEncoding ( "utf-8") ; // set the encoding format  

  XMLWriter xmlWriter;

try {

xmlWriter = new XMLWriter(new FileOutputStream(path),format);

 xmlWriter.write(root);  

     xmlWriter.close();

} catch (UnsupportedEncodingException | FileNotFoundException e) {

  e.printStackTrace ();

  throw new RuntimeException(e);

} catch (IOException e) {

 e.printStackTrace ();

  throw new RuntimeException(e);

}

}


/**

 *

 * @param element

 * @Param path   indicates the path and file name

 */

public static void writeXML(Element root,String path) {

function () {// Spread http://www.fx61.com/faq/HantecGlobal/480.html

OutputFormat format = new OutputFormat("    ",true);  

  format.setEncoding ( "utf-8") ; // set the encoding format  

  XMLWriter xmlWriter;

try {

xmlWriter = new XMLWriter(new FileOutputStream(path),format);

 xmlWriter.write(root);  

     xmlWriter.close();

} catch (UnsupportedEncodingException | FileNotFoundException e) {

  e.printStackTrace ();

  throw new RuntimeException(e);

} catch (IOException e) {

  e.printStackTrace ();

  throw new RuntimeException(e);

}

}


 public static String jsonToXML(String json) {

 try {

    net.sf.json.xml.XMLSerializer xmlSerializer = new net.sf.json.xml.XMLSerializer();

        // root name

        xmlSerializer.setRootName("resource");

        // 不对类型进行设置

        xmlSerializer.setTypeHintsEnabled(false);

        String xmlStr = "";

        JSONObject jobj = JSONObject.fromObject(json);

        xmlStr = xmlSerializer.write(jobj);

        return xmlStr;

} catch (Exception e) {

// TODO: handle exception

  throw new RuntimeException(e);

 }

       

    }

 

}

 


Guess you like

Origin blog.51cto.com/14511863/2462393