XML字符串解析

不多说,直接上代码:

import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

//转化XML字符串

public Element parseXML(String strXML){
  Element source = null;
  strXML =this.transFromXmlStr(strXML);
  if("".equals(strXML)||"null".equals(strXML)){
  return source;
  }
  SAXReader reader = new SAXReader();
  StringReader sr = new StringReader(strXML);
  InputSource is = new InputSource(sr);
  Document document;
  try {
    document = reader.read(is);
    source = document.getRootElement();
  } catch (DocumentException e) {
    e.printStackTrace();
  }
  return source;
}

//特殊字符处理

public static String transToXmlStr(String text) {
  if (text == null)
  return "";
  String tmp = text.replace(">", "&rt;");
  tmp = tmp.replace(""", """);
  tmp = tmp.replace("<", "&lt;");
  tmp = tmp.replace("
", "&#13;");
  tmp = tmp.replace("
", "&#10;");
  tmp = tmp.replace("&", "&amp;");
  return tmp;
}

//获取XML信息

public void getXML(Element root){  

  if(root!=null){
  Element rwxx = root.element("rwxx");
  List<Element> rows = rwxx.elements("row");
  for(Element row : rows){
    Element id = row.element("id");

    Element name = row.element("name");

    if(id!=null){

      System.out.println("id:"+id.getText());

    }

    if(name!=null){

      System.out.println("name:"+name.getText());

    }

  }

}
版权声明:如需转载,请注明!PS:如是转载随便,请忽略
原文地址:https://www.cnblogs.com/zwdx/p/7193536.html