2011-10-13 15 views
0

海蘭, 我有又有些問題,我的XML解析器:dXML解析Document.parse以外的名稱錯誤

我解析字符串org.w3c.dom.Document中 他代碼:

String str = new String(IOUtilities.streamToBytes(is), "UTF-8"); 
InputSource source = new InputSource(); 
source.setCharacterStream(new StringReader(str)); 
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
dbf.setCoalescing(true); 
dbf.setAllowUndefinedNamespaces(true); 
DocumentBuilder db; 
Document doc = null; 

db = dbf.newDocumentBuilder(); 
doc = db.parse(source); // ERROR here 
doc.getDocumentElement().normalize(); 

但我得到一個錯誤信息:期待一個名字

的字符串(重新格式化爲可讀):

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
    <soap:Fault> 
     <faultcode>soap:Server</faultcode> 
     <faultstring>Server was unable to process request. ---&gt; Invalid Username or password</faultstring> 
     <detail /> 
    </soap:Fault> 
    </soap:Body> 
</soap:Envelope> 

回答

0

試試這個

DocumentBuilderFactory factory1 = DocumentBuilderFactory.newInstance(); 

DocumentBuilder builder1 = factory1.newDocumentBuilder(); 

XMLDOMUtil xm1 = new XMLDOMUtil(); 

ByteArrayInputStream bis = new ByteArrayInputStream(res.getBytes("UTF-8")); 

Document document = builder1.parse(bis); 

Node root = xm1.getNodeByTag(document, "soap:Envelope"); 

Node nextroot= xm1.getNodeByTag(root,"soap:Body"); 

Node nextroot1= xm1.getNodeByTag(nextroot,"soap:Fault"); 

String faultstring= xm1.getNodeTextByTag(nextroot1,"faultstring"); 

XMLDOMUtil類給出如下─

import org.w3c.dom.Node; 
import org.w3c.dom.Text; 

public class XMLDOMUtil { 



// go thru the list of childs and find the text associated by the tag 
public String getNodeTextByTag(Node parentNode, String name) { 

    Node node = parentNode.getFirstChild(); 
    Text text = null; 
    String retStr = null; 

    try { 
     while (node != null) { 
      if (node.getNodeName().equals(name)) { 
       text = (Text) node.getFirstChild(); 
       retStr = text.getData(); 
       break; 
      } 
      node = node.getNextSibling(); 
     } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return retStr; 
} 

public Node getNodeByTag(Node parentNode, String name) { 

    Node node = parentNode.getFirstChild(); 
    Node retNode = null; 

    while (node != null) { 
     if (node.getNodeName().equals(name)) { 
      retNode = node; 
      break; 
     } 
     node = node.getNextSibling(); 
    } 
    return retNode; 
} 

public Node getNextSiblingNodeByTag(Node siblingNode, String name) { 

    Node retNode = null; 

    siblingNode = siblingNode.getNextSibling(); 

    while (siblingNode != null) { 
     if (siblingNode.getNodeName().equals(name)) { 
      retNode = siblingNode; 
      break; 
     } 
     siblingNode = siblingNode.getNextSibling(); 
    } 
    return retNode; 
} 

}