2012-07-03 83 views
0

我需要修復以下用於XML數據注入的代碼。響應中的XML數據注入來自Web服務的XML

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = factory.newDocumentBuilder(); 
InputSource inStream = new InputSource(); 
inStream.setCharacterStream(new StringReader(xmlFromWebService)); 
Document doc = db.parse(inStream); // reported at this line by a code audit tool 
doc.getDocumentElement().normalize(); 

如何解決?有沒有人有任何建議。

+0

你我關心你了。而且,在我的模塊中找到並實施解決方案並對其進行測試後,我對每個問題發佈了正確的解決方案。我不知道它。 –

+0

嘿你可以給這個解決方案吧!!!!! –

回答

1

我猜測這與你的XML對一個給定的XSD的驗證有關,以防止XML數據注入。我建議你這樣修改你的代碼:

try { 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    factory.setNamespaceAware(true); 
    factory.setValidating(true); 

    factory.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
         "http://www.w3.org/2001/XMLSchema"); 
    factory.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", 
         "file:<your_xsd_file>"); 

    DocumentBuilder builder = factory.newDocumentBuilder(); 
    InputSource inStream = new InputSource(); 
    inStream.setCharacterStream(new StringReader(xmlFromWebService)); 
    Document document = builder.parse(inStream); 

} catch (ParserConfigurationException e) { 
    e.printStackTrace(); 
} catch (SAXException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

我希望你能得到提示!

+0

雅我明白了。還做了一些相同的研發。你能告訴我,這個setProperty設置了什麼屬性?我將setAttribute作爲實際名稱。它會以同樣的方式工作嗎?此外,這些屬性的價值應該是什麼?另外所有的東西是如何完成documentBuilderFactory的工作的? –

+0

@ R.K.R:1. SchemaLanguage&Schema Source(這就是爲什麼我將第二個屬性的值有意地保存爲)。 2. setAttribute也可以工作。在我的代碼中閱讀這兩行,並且您可以理解該值的用途。 3.我不太明白你問題的最後部分是什麼意思。 – Sujay

+0

我的意思是如何documentBuilderfactory將驗證所有的東西xml?我用它做的任何方式都能找到問題的所有解決方案,並且還實施了演示解決方案並獲得客戶的認可。非常感謝!!!!!! 1 –