0

我需要为 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();

如何解决?有没有人有什么建议。

4

1 回答 1

1

我猜这与针对给定 XSD 验证您的 XML 以防止 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();
}

我希望你得到提示!

于 2012-07-04T04:48:06.033 回答