解析包含dtd引用的xml文件。

当我们解析包含dtd的xml文件的时候,尤其是在内网环境,无法连接网络的情况下,会无法进行下载DTD文件而报错。这个时候需要进行设置。实现代码如下:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


public static boolean wljxptXmlDataSourceUpdate(String filePath,
DataSourcePojo dataSourcePojo) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
//不用校验dtd文件
db.setEntityResolver(new EntityResolver() {
@SuppressWarnings("deprecation")
public InputSource resolveEntity(String publicId,
String systemId) throws SAXException, IOException {
return new InputSource(new StringBufferInputStream(""));
// return null;//这个的效果仍然是从网络来抓取DTD来验证
}
});
Document doc = db.parse(filePath);
NodeList list = doc
.getElementsByTagName(DataSourcePropertyFactory.WLJXPT_REPLACE_NODE_NAME);
for (int i = 0; i < list.getLength(); i++) {
Element e = (Element) list.item(i);
if (e.getAttribute("name").equals(DataSourcePropertyFactory.WLJXPT_REPLACE_NODE_ATTRIBUTE_JDBCURL)) {
String driverUrl ="jdbc:oracle:thin:"+dataSourcePojo.getUserId()+"/"+ dataSourcePojo.getUserPwd()
+"@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST="+dataSourcePojo.getIpAddress()+")(PORT="+dataSourcePojo.getPort()
+"))(FAILOVER=on)(LOAD_BALANCE=on))"+
"(CONNECT_DATA= (SERVICE_NAME="+dataSourcePojo.getDbname()+")))";
e.setAttribute("value", driverUrl);
} else if (e.getAttribute("name").equals(DataSourcePropertyFactory.WLJXPT_REPLACE_NODE_ATTRIBUTE_USER)) {
e.setAttribute("value", dataSourcePojo.getUserId());
} else if (e.getAttribute("name").equals(DataSourcePropertyFactory.WLJXPT_REPLACE_NODE_ATTRIBUTE_PASSWORD)) {
e.setAttribute("value", dataSourcePojo.getUserPwd());
}
}


TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer tf = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StreamResult result = new StreamResult(new FileOutputStream(
filePath));
tf.transform(domSource, result);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

你可能感兴趣的:(xml,exception,String,list,jdbc,service)