Java如何在JDOM中浏览XML元素树?
package org.nhooo.example.jdom;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
public class JDOMTraversingElement {
public static void main(String[] args) {
String xml = "<root>" +
" <country name=\"Japan\" capital=\"Tokyo\"/>" +
" <country name=\"France\" capital=\"Paris\"/>" +
" <country name=\"Italy\" capital=\"Rome\"/>" +
" <country name=\"England\" capital=\"London\"/>" +
" <country name=\"Indonesia\" capital=\"Jakarta\"/>" +
" <city name=\"Denpasar\"/>" +
" <city name=\"Bangkok\"/>" +
" <city name=\"Mumbai\"/>" +
" <city name=\"Delhi\"/>" +
"</root>";
SAXBuilder builder = new SAXBuilder();
try {
Document document = builder.build(
new ByteArrayInputStream(xml.getBytes()));
//获取根元素
Element root = document.getRootElement();
//生第一个孩子
Element country = root.getChild("country");
System.out.println("Name: " + country.getAttribute("name")
.getValue());
System.out.println("Capital: " + country.getAttribute("capital")
.getValue());
System.out.println("----------------------------------------");
//让所有的孩子都扎根
List<Element> elements = root.getChildren();
for (Element element : elements) {
if (element.getName().equals("country")) {
System.out.println(MessageFormat.format("{0} -> {1}",
element.getAttribute("name").getValue(),
element.getAttribute("capital").getValue()));
} else if (element.getName().equals("city")) {
System.out.println(element.getAttribute("name")
.getValue());
}
}
System.out.println("----------------------------------------");
//让所有的孩子都扎根 named city
List<Element> cities = root.getChildren("city");
for (Element city : cities) {
System.out.println(city.getAttribute("name").getValue());
}
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
}
}代码段的结果是:
Name: Japan Capital: Tokyo ---------------------------------------- Japan -> Tokyo France -> Paris Italy -> Rome England -> London Indonesia -> Jakarta Denpasar Bangkok Mumbai Delhi ---------------------------------------- Denpasar Bangkok Mumbai Delhi
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>