2011-11-11 21 views
0

我試圖將XML字符串解析爲可用於輕鬆搜索的文檔。但是當我遇到某種類型的XML時,它似乎不起作用。該文檔從不構造,並且在遇到像我在底部的XML消息時爲空。一個錯誤時拋出是不是在我的try/catch拋出的任何使用Java解析XSI

我的代碼目前看起來是這樣的:

Document convertMessageToDoc(String message){ 
     Document doc = null; 

     try { 
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
      dbf.setNamespaceAware(true); 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      InputSource is = new InputSource(); 
      is.setCharacterStream(new StringReader(message)); 

      doc = db.parse(is); 
     } 
     catch (Exception e) { 
      //e.printStackTrace(); 
      doc = null; 
     } 

     return doc; 
    } 

有什麼辦法,我將能夠與這樣的工作:

<ns1:SubmitFNOLResponse xmlns:ns1="http://website.com/"> 
<ns1:FNOLReporting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns1:FNOLReporting"> 
<ns1:FNOLResponse> 
<ns1:FNOLStatusInfo> 
    <ns1:StatusCode>0</ns1:StatusCode> 
    <ns1:StatusMessages /> 
    </ns1:FNOLStatusInfo> 
    </ns1:FNOLResponse> 
    </ns1:FNOLReporting> 
    </ns1:SubmitFNOLResponse> 
+0

你能定義「不行」嗎? –

+0

我已澄清我的問題 – user906153

+0

它真的沒有封閉標籤嗎?從技術上講,我不確定它會保持原樣。沒有例外,因爲當有一個時,你什麼都不做。 –

回答

0

您的文檔不是格式良好的XML。一旦成功,一切似乎都按預期工作。

String message = 
     "<ns1:Prods xmlns:ns1='/foo'>"// xmlns:ns1='uri'>" 
       + "<ns1:Prod>" 
       + " <ns1:ProductID>316</ns1:ProductID>" 
       + "  <ns1:Name>Blade</ns1:Name>" 
       + "</ns1:Prod>" 
       + "<ns1:Prod>" 
       + " <ns1:ProductID>317</ns1:ProductID>" 
       + " <ns1:Name>LL Crankarm</ns1:Name>" 
       + " <ns1:Color>Black</ns1:Color>" 
       + "</ns1:Prod>" 
       + "</ns1:Prods>"; 

Document doc = null; 

try { 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    dbf.setNamespaceAware(true); 
    dbf.setValidating(false); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    InputSource is = new InputSource(); 
    is.setCharacterStream(new StringReader(message)); 
    doc = db.parse(is); 

    NodeList sections = doc.getElementsByTagName("ns1:Prod"); 
    int numSections = sections.getLength(); 
    for (int i = 0; i < numSections; i++) { 
     Element section = (Element) sections.item(i); 
     NodeList prodinfos = section.getChildNodes(); 
     for (int j = 0; j < prodinfos.getLength(); j++) { 
      Node info = prodinfos.item(j); 
      if (info.getNodeType() != Node.TEXT_NODE) { 
       System.out.println(info.getNodeName() + ": " + info.getTextContent()); 
      } 
     } 
     System.out.println(""); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
    doc = null; 
} 

// Outputs 

ns1:ProductID: 316 
ns1:Name: Blade 

ns1:ProductID: 317 
ns1:Name: LL Crankarm 
ns1:Color: Black 
+0

我編輯了我的示例XML,使其更接近我正在使用的內容 – user906153

+1

@ user906153那真是浪費我的時間。對於新的XML仍然可以正常工作;看到我的代碼訪問元素和兒童。儘管如此,我肯定會推薦一種更簡單的方法,比如dom4j/jaxb /等。而不是手動做所有事情 - xpath使一切變得更容易。 –

1

它看起來像你的文件不是「格式良好」。您需要一個根元素,其中在根處有兩個兄弟「ns1:Prod」標籤。

+0

我編輯了我的示例XML,使其與我正在處理的內容 – user906153

+0

+1非常接近,即使我已經在我的評論中說過:) –