首页 > 代码库 > XML字符串解析

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("\r", "&#13;");
  tmp = tmp.replace("\n", "&#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());

    }

  }

}

XML字符串解析