也许您可以尝试使用 XPath。您可以查询节点的 NodeList 并获取通过节点列表迭代的名称
就像是:
public NodeList nodeListByXPath(Node xml,
String theXPath) throws XPathExpressionException {
NodeList outNodes = (NodeList)_xPath(xml,theXPath,XPathConstants.NODESET);
return outNodes;
}
private Object _xPath(Node xml,
String theXPath,
QName returnType) throws XPathExpressionException {
Object outObj = null;
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression xPathExpr = xPath.compile(theXPath.trim());
if (returnType == XPathConstants.BOOLEAN) {
outObj = xPathExpr.evaluate(xml,XPathConstants.BOOLEAN);
} else if (returnType == XPathConstants.NUMBER) {
outObj = xPathExpr.evaluate(xml,XPathConstants.NUMBER);
} else if (returnType == XPathConstants.STRING) {
outObj = xPathExpr.evaluate(xml,XPathConstants.STRING);
} else if (returnType == XPathConstants.NODE) {
outObj = xPathExpr.evaluate(xml,XPathConstants.NODE);
} else if (returnType == XPathConstants.NODESET) {
outObj = xPathExpr.evaluate(xml,XPathConstants.NODESET);
}
return outObj;
}
public Document parse(InputStream is) throws SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setValidating(false);
factory.setIgnoringElementContentWhitespace(true);
factory.setNamespaceAware(false);
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
InputSource ins = new InputSource(is);
Document doc = builder.parse(ins);
return doc;
} catch (ParserConfigurationException pcEx) {
throw new SAXException(pcEx);
} catch (IOException ioEx) {
throw new SAXException(ioEx);
}
}
您只需致电:
Document doc = parse(is);
NodeList nl = nodeListByXPath(doc.getDocumentElement(),
"/catalog/cd/title");
现在遍历节点