我正在使用Eclipse编写一个Java servlet(将在Google App Engine上托管),需要处理一个XML文档。有哪些库可以轻松添加到Eclipse项目中,并且具有良好的示例代码?
我最终使用了SAX API和JAXP。
在我的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安装中进行了配置。
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;
}
你可以在非servlet环境下使用完全相同的库。