這裏是我的XML代碼使用循環讀取XML子節點的值...如何通過java的
<flow>
<TaskID>100</TaskID>
<TaskID>101</TaskID>
<TaskID>102</TaskID>
<TaskID>103</TaskID>
</flow>
我想知道如何獲得任務id值在Java中循環。請幫我...
這裏是我的XML代碼使用循環讀取XML子節點的值...如何通過java的
<flow>
<TaskID>100</TaskID>
<TaskID>101</TaskID>
<TaskID>102</TaskID>
<TaskID>103</TaskID>
</flow>
我想知道如何獲得任務id值在Java中循環。請幫我...
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文件較大,如MB/GB的100S或者你是一個低內存的平臺上再考慮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);
我正在使用DOM解析器來解析輸入文件。通過使用
@ user1820087我已更新我的解決方案,以便有更復雜的輸入來表示您的問題。我建議使用XPath來處理這種類型的問題,因爲表達式只是「// flow/TaskID/text()」,而不需要通過getChildNodes()等循環。 – Adam
爲什麼使用NODESET XPathConstant? – Wronski
使用XPath下面是詳細信息:
下面是使用JDOM,它比現有的Java XML解析器提供了更舒適的API的例子:
import java.io.File;
import org.jdom2.*;
import org.jdom2.input.*;
public class Test {
// TODO: More appropriate exception handling :)
public static void main (String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("test.xml"));
Element root = doc.getRootElement();
for (Element element : root.getChildren("TaskID")) {
System.out.println(element.getText());
}
}
}
當然,這是假設XML文檔足夠小,可以加載到內存中。 (很明顯,你也可以使用內置的庫,如果你沒有在做很多 XML的工作,那麼這將是很好 - 我只是發現它們有點原始,如果你做任何大量的工作)。
我個人使用JDOM庫來處理我所有的XML操作。下面是我該怎麼做;
String xml = "<flow> " +
"<TaskID>100</TaskID>" +
"<TaskID>101</TaskID>" +
"<TaskID>102</TaskID>" +
"<TaskID>103</TaskID>" +
"</flow>";
org.jdom.Document doc = new SAXBuilder().build(new StringReader(xml));
org.jdom.Element rootElement = doc.getRootElement();
List<Element> eles = rootElement.getChildren("TaskID");
for(Element el : eles)
System.out.println(el.getName()+" : "+el.getValue());
你可以得到它的文檔在這裏:http://www.jdom.org/
讀取XML兒童SAX
<?xml version="1.0"?>
<Patriarch>
<name>Bill</name>
<wife>
<name>Vi</name>
</wife>
<son>
<name>Bill</name>
</son>
<daughter>
<name>Jeri</name>
<husband>
<name>Mark</name>
</husband>
<son>
<name>Greg</name>
</son>
<son>
<name>Tim</name>
</son>
<son>
<name>Mark</name>
</son>
<son>
<name>Josh</name>
<wife>
<name>Kristine</name>
</wife>
<son>
<name>Blake</name>
</son>
<daughter>
<name>Liah</name>
</daughter>
</son>
</daughter>
</Patriarch>
和Java代碼:
public class ParseXmlSAX {
public static void main(String[] args) {
new ParseXmlSAX("file.xml");
}
public ParseXmlSAX(final String file) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
String key = null;
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (key == null)
key = "|";
else
key += qName + "|";
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (!key.equals("|"))
key = key.substring(0, key.lastIndexOf(qName));
}
public void characters(char ch[], int start, int length) throws SAXException {
String conteudo = new String(ch, start, length).trim();
if (!conteudo.isEmpty()) {
System.out.println(key + " = " + conteudo);
}
}
};
saxParser.parse(this.getClass().getResourceAsStream(file), handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
您使用的XML和Java綁定庫,例如JAXB使用Java中的XML? –
+1。不要嘗試使用正則表達式。 – bdares
你有什麼嘗試? XML特別大嗎?你能夠使用第三方庫,如jdom? –