这是我的 xml 代码...
<flow>
<TaskID>100</TaskID>
<TaskID>101</TaskID>
<TaskID>102</TaskID>
<TaskID>103</TaskID>
</flow>
我想知道如何在 java 中的 for 循环中获取 taskID 值。请帮助我...
最佳答案
DOM 解析器解决方案,相当简单,不需要额外的库。
public static void main(String[] args) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String input = "<outer>";
input += "<otherstuff><TaskID>123</TaskID></otherstuff>";
input += "<flow>";
input += "<TaskID>100</TaskID>";
input += "<TaskID>101</TaskID>";
input += "<TaskID>102</TaskID>";
input += "<TaskID>103</TaskID>";
input += "</flow>";
input += "</outer>";
Document document = builder.parse(new InputSource(new StringReader(
input)));
NodeList flowList = document.getElementsByTagName("flow");
for (int i = 0; i < flowList.getLength(); i++) {
NodeList childList = flowList.item(i).getChildNodes();
for (int j = 0; j < childList.getLength(); j++) {
Node childNode = childList.item(j);
if ("TaskID".equals(childNode.getNodeName())) {
System.out.println(childList.item(j).getTextContent()
.trim());
}
}
}
}
如果您的输入来自文件,则需要使用 FileReader。
Document document = builder.parse(new InputSource(new FileReader(
new File("foo.xml"))));
getElementsByTagName() 的替代方法是 XPath,这是一种 XML 查询语言,如果您要匹配复杂的条件集,这将特别有用。
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//flow/TaskID/text()");
Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getTextContent());
}
如果您的 XML 文件很大,例如 100 MB/GB,或者您使用的是低内存平台,那么请考虑使用 SAX 解析器。
String input = "<flow><TaskID>100</TaskID><TaskID>101</TaskID><TaskID>102</TaskID><TaskID>103</TaskID></flow>";
SAXParser sax = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new DefaultHandler() {
private StringBuilder buffer = new StringBuilder();
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("TaskID".equals(qName)) {
System.out.println(buffer);
buffer = new StringBuilder();
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buffer.append(ch, start, length);
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
buffer = new StringBuilder();
}
};
sax.parse(new InputSource(new StringReader(input)), handler);
关于java - 如何在 java 中使用循环读取 XML 子节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13356534/