Dom4j解析节点带前缀的XML文档(命名空间)

import java.io.StringReader;
import java.util.HashMap;

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

 


public class Test {
 
 
 //获取document对象
  public Document getDocument(String xml) throws DocumentException
  {
   StringReader read = new StringReader(xml);
      //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
      InputSource source = new InputSource(read);
      //创建一个新的SAXBuilder
      SAXReader sb = new SAXReader();
    
          //通过输入源构造一个Document
      Document doc = sb.read(source);
          //取的根元素
      return doc;
  }
 
  //获取带有命名空间的节点
  public Element getDestElement(Document doc)
  {
   HashMap xmlMap = new HashMap();
   xmlMap.put("tns","
http://www.99bill.com/schema/fo/settlement");
  
   XPath xpath=doc.createXPath("//tns:status"); //要获取哪个节点,改这里就可以了
   xpath.setNamespaceURIs(xmlMap);
   return (Element)xpath.selectSingleNode(doc);
  }


 
 public void jie()
 {
  String b=
   ""+
     ""+
       ""+
         "1.0.1"+
         "fo.api.query"+
       "
"+
       "20100811160633"+
     "
"+
     ""+
       ""+
         "SZ0806003"+
         "1"+
         "20"+
         "0"+
       "
"+
       "1"+
       "2"+
       ""+
         "1001162953701"+
         "SZ0806003"+
         "20100806103600"+
         "大批量结算产品测试账户005"+
         "10000"+
         "2"+
         "1"+
         "RMB"+
         "0"+
         "1"+
         "0"+
         "0"+
         "0"+
         "memo1"+
         "memo2"+
         "memo3"+
         "111"+
         "7368788"+
         "10000"+
         "2"+
         "1000"+
         "20100806105604"+
         ""+
         ""+
           ""+
             "20100806103600"+
             "20100806105604"+
             "7369556"+
             "500"+
             "112"+
             "9113"+
             "客户姓名不符"+
             ""+
             ""+
             ""+
               "20100806_005"+
               "快钱交易备注"+
               "理赔"+
               "银行交易备注"+
               "付款"+
               "13891819014"+
               "[email protected]"+
               ""+
               "1"+
               "2"+
               "3"+
             "
"+
           "
"+
         
         "
"+
       "
"+
     "
"+
   "
";
  
  
  try {
   Document doc=this.getDocument(b);
   Element el=this.getDestElement(doc);
   System.out.println("*********"+el.getText());
   
   
  } catch (DocumentException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }


 }
 

 public static void main(String[] args) {
  
  Test t=new Test();
  t.jie();
  

 }

}

你可能感兴趣的:(Dom4j解析节点带前缀的XML文档(命名空间))