1. 样例xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<name type="String">aaa</name>
<age type="int">22</age>
</student>
<student>
<name type="String">bbb</name>
<age type="int">23</age>
</student>
<student>
<name type="String">ccc</name>
<age type="int">21</age>
</student>
</students>
2. 读入各种形式的xml
2.1 读入文件
SAXReader reader = new SAXReader();
Document document = reader.read(new File("d:/tmp/3.xml"));
2.2 读入文件内容(字符串)
String text = "<?xml version="1.0" encoding="UTF-8"?><students> <student> <name type="String">aaa</name> <age type="int">22</age> </student> <student> <name type="String">bbb</name> <age type="int">23</age> </student> <student> <name type="String">ccc</name> <age type="int">21</age> </student></students>";
Document document = DocumentHelper.parseText(text);
2.3 读入网络URL
String url = "http://www.webservicex.net/globalweather.asmx?wsdl";
SAXReader reader = new SAXReader();
URL realUrl = new URL(url);
Document document = reader.read(realUrl);
3. 获得节点与属性
在得到document之后,可以得到该xml的所有节点与属性。
Element rootElement = document.getRootElement();
if (rootElement == null) {
return "";
}
Element se = rootElement.element("types");
if (se == null) {
return "";
}
Element se1 = se.element("schema");
if (se1 == null) {
return "";
}
Element se2 = se1.element("element");
if (se2 == null) {
return "";
}
return se2.attributeValue("name");