2010-08-19 56 views
0

解析使用XPath表達式/ABCDE /響應從XML,與dom4j的

<abcde> 
      <response>000</response> 
</abcde> 

我成功地檢索的響應數據,但不可能從相同的XML檢索響應的數據,但與一些額外的數據

<abcde version="8.1" xmlns="http://www.litle.com/schema" 
     response="0" message="Valid Format"> 
      <response>000</response> 
</abcde> 

我做錯了什麼?

回答

2
package stackoverflow; 
import java.io.ByteArrayInputStream; 
import java.util.HashMap; 
import java.util.Map; 
import org.dom4j.Document; 
import org.dom4j.DocumentException; 
import org.dom4j.DocumentFactory; 
import org.dom4j.DocumentHelper; 
import org.dom4j.XPath; 
import org.dom4j.io.SAXReader; 
import org.dom4j.xpath.DefaultXPath; 
import org.jaxen.VariableContext; 

public class MakejdomWork { 
    public static void main(String[] args) { 
     new MakejdomWork().run(); 
    } 

    public void run() { 
     ByteArrayInputStream bis = new ByteArrayInputStream("<abcde version=\"8.1\" xmlns=\"http://www.litle.com/schema\"  response=\"0\" message=\"Valid Format\">   <response>000</response></abcde>".getBytes()); 
     //ByteArrayInputStream bis = new ByteArrayInputStream("<abcde><response>000</response></abcde>".getBytes()); 

     Map nsPrefixes = new HashMap(); 
     nsPrefixes.put("x", "http://www.litle.com/schema"); 

     DocumentFactory factory = new DocumentFactory(); 
     factory.setXPathNamespaceURIs(nsPrefixes); 

     SAXReader reader = new SAXReader(); 
     reader.setDocumentFactory(factory); 
     Document doc; 
     try { 
      doc = reader.read(bis); 
      Object value = doc.valueOf("/abcde/x:response"); 
      System.out.println(value); 
     } catch (DocumentException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

簡短的回答:您需要使用命名空間前綴,如果您的解析器感知名稱空間(這是DOM4J)