欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

xml 处理空节点,xml处理节点,import java.

来源: javaer 分享于  点击 13881 次 点评:186

xml 处理空节点,xml处理节点,import java.


import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;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.apache.commons.lang.StringUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.xml.sax.InputSource;public class test {  private static Log log = LogFactory.getLog(test.class);  public String process(String result) {    if (log.isDebugEnabled()) {      log.debug("test ");    }    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    DocumentBuilder builder;    try {      builder = factory.newDocumentBuilder();      Document doc = builder.parse(new InputSource(new StringReader(result)));      handleNode(doc);      result = xmlToString(doc);    } catch (Exception e) {      // TODO Auto-generated catch block      log.error(e.getLocalizedMessage());    }    return result;  }  private static void handleNode(Node node) {    if (node.getChildNodes().getLength() == 0        && StringUtils.isBlank(node.getNodeValue())) {      Node parentNode = node.getParentNode();      parentNode.removeChild(node);      handleNode(parentNode);      return;    }    for (int i = 0; i < node.getChildNodes().getLength(); i++) {      handleNode(node.getChildNodes().item(i));    }  }  private String xmlToString(Document doc) throws IOException {    TransformerFactory transfac = TransformerFactory.newInstance();    StringWriter sw = new StringWriter();    String xmlString = "";    try {      Transformer trans = transfac.newTransformer();      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");      trans.setOutputProperty(OutputKeys.METHOD, "xml");      trans.setOutputProperty(OutputKeys.INDENT, "yes");      trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");      trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");      StreamResult result = new StreamResult(sw);      DOMSource source = new DOMSource(doc);      trans.transform(source, result);      xmlString = sw.toString();    } catch (Exception e) {      log.error(e.getLocalizedMessage());    } finally {      sw.close();    }    return xmlString;  }    public static void main(String[] args){        String str = "<a><b>5555</b><c><e>666</e><f></f><m><n>7777</n></m></c><p></p></a>";        ACORDResultProcesser aCORDResultProcesser = new ACORDResultProcesser();        String xml = aCORDResultProcesser.process(str);    }}//该片段来自于http://byrx.net
相关栏目:

用户点评