我正在编写一个 Java servlet在 Eclipse 中(将托管在 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();
....
关于java - 有哪些库可以在 Google App Engine/Java Servlet 上处理 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1032724/