【发布时间】:2019-09-05 13:46:05
【问题描述】:
我正在尝试从 S.O. 的 Java 专家那里获得一些帮助。关于这个问题。我在一个长期项目中遇到了 XMLParser 的旧实现...... 在我看来,这个实现是不正确的,或者可以改进.. 我想知道是否有人可以指出该怎么做,非常感谢您的意见......
这是一个带有 pom.xml 的 maven 项目,用于依赖 btw...
问题...
所以基本上有人在项目中直接从 IBM 内部 JRE 中使用了 SAXParser 类...
我怎样才能将这种和平的代码转换为不受 WAS(Websphere 应用服务器)的依赖?
public boolean parse(){
boolean res = false;
try {
SAXParser p = new SAXParser(); // Need to replace this for better aproach
p.setContentHandler(this); // Need to replace this for better aproach
InputSource inputSource = new InputSource(new StringReader(source));
if (inputSource != null){
p.parse(inputSource); // Need to replace this for better aproach
}
res = true;
}
catch (Exception e) {
System.err.println("public void parse()"+e.getLocalizedMessage());
res= false;
e.printStackTrace();
}
return res;
}
更新
迁移成功:)
...
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
...
public boolean parse(){
boolean res = false;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(this);
InputSource inputSource = new InputSource(new StringReader(source));
if (inputSource != null){
xmlReader.parse(inputSource);
}
res = true;
}
catch (Exception e) {
System.err.println("public void parse()"+e.getLocalizedMessage());
res= false;
e.printStackTrace();
}
return res;
}
【问题讨论】:
标签: java xml-parsing saxparser