【发布时间】:2010-11-05 04:28:20
【问题描述】:
我正在 Eclipse 中编写 Java servlet(将托管在 Google App Engine 上)并且需要处理 XML 文档。哪些库易于添加到 Eclipse 项目并具有良好的示例代码?
【问题讨论】:
我正在 Eclipse 中编写 Java servlet(将托管在 Google App Engine 上)并且需要处理 XML 文档。哪些库易于添加到 Eclipse 项目并具有良好的示例代码?
【问题讨论】:
我最终将JAXP 与 SAX API 一起使用。
在我的 servlet 中添加如下内容:
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
....
InputStream in = connection.getInputStream();
InputSource responseXML = new InputSource(in);
final StringBuilder response = new StringBuilder();
DefaultHandler myHandler = new DefaultHandler() {
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("elementname")) {
response.append(attributes.getValue("attributename"));
inElement = true;
}
}
public void characters(char [] buf, int offset, int len) {
if (inElement) {
inElement = false;
String s = new String(buf, offset, len);
response.append(s);
response.append("\n");
}
}
};
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
parser.parse(responseXML, myHandler);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.close();
connection.disconnect();
....
【讨论】:
Xerces(提供 SAX 和 DOM 实现)和 Xalan(提供对转换的支持) - 自 1.5 以来都与 JDK 捆绑在一起,因此已经在标准 Java 安装中进行了配置
【讨论】:
您可以使用需要 xerces SAXParser 的 JDOM。但是,AppEngine 不提供 xerces 库。您可以通过将其复制到项目的 WEB-INF/lib 文件夹中来添加它。
【讨论】:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String content = req.getParameter("content");
Document doc = parseXml(content);
resp.setContentType("text/plain");
if (doc != null)
{
resp.getWriter().println(doc.getDocumentElement().getNodeName());
}
else
{
resp.getWriter().println("no input/bad xml input. please send parameter content=<xml>");
}
}
private static Document parseXml(String strXml)
{
Document doc = null;
String strError;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
StringReader reader = new StringReader( strXml );
InputSource inputSource = new InputSource( reader );
doc = db.parse(inputSource);
return doc;
}
catch (IOException ioe)
{
strError = ioe.toString();
}
catch (ParserConfigurationException pce)
{
strError = pce.toString();
}
catch (SAXException se)
{
strError = se.toString();
}
catch (Exception e)
{
strError = e.toString();
}
log.severe("parseXml: " + strError);
return null;
}
【讨论】:
JDom 具有比标准 Java XML api 更好(更简单)的接口。
【讨论】:
您可以使用在非 servlet 环境中使用的完全相同的库。
【讨论】:
另一个比 Xerces 速度更快的选择(我上次比较它们时)是Saxon。
【讨论】: