DOM 的使用

DOM 的使用

package com.sunrise.ocs.webservice.unicom.test;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class TestDom {
 
 //将xml串转换为document
 public static Document xml2Document(String xml) {
  Document doc = null;
  try {
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   doc = builder.parse(new InputSource(new StringReader(xml)));
  } catch (Exception e) {
   e.printStackTrace();
  }
  return doc;
 }
 
 //将xml文件串转换为document
 public static Document xmlFile2Document(String xmlFile) {
  Document doc = null;
  try {
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   doc = builder.parse(new File(xmlFile));
  } catch (Exception e) {
   e.printStackTrace();
  }
  return doc;
 }
 
 //删除命名空间: xmlns="..."
 public static String delNamespace(String xml) {
  String result = xml;
  try {
   Document doc = xml2Document(xml);
   Element root = doc.getDocumentElement();
   root.removeAttribute("xmlns");
   result = asXml(doc);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return result;
 }
 
 //将doc转换为xml串
 public static String asXml(Document doc) {
  String strxml = "";
  try {
   OutputFormat format = new OutputFormat(doc);
   // format.setEncoding("UTF-8");
   StringWriter stringOut = new StringWriter();
   XMLSerializer serial = new XMLSerializer(stringOut, format);
   serial.asDOMSerializer();
   serial.serialize(doc.getDocumentElement());
   strxml = stringOut.toString();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return strxml;
 }
 
 //将node转换为xml串
 public static String asXml(Node node, Document doc) {
  String strxml = "";
  try {
   OutputFormat format = new OutputFormat(doc);
   // format.setEncoding("UTF-8");
   StringWriter stringOut = new StringWriter();
   XMLSerializer serial = new XMLSerializer(stringOut, format);
   serial.asDOMSerializer();
   serial.serialize((Element)node);
   strxml = stringOut.toString();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return strxml;
 }
}

你可能感兴趣的:(DOM 的使用)