/**
* 根据标签名递归读取xml字符串中element
* 例:
* String xml =
* "\n" +
* " \n" +
* "\n" +
* " \n" +
* " \n" +
* " \n" +
* " ";
*
* element(xml) => 获得 req element
* element(xml, "tag1") => 获得 tag1 element
* element(xml, "tag2", "tag4") => 获得 tag4 element
*
* @param xml
* @param nodes
* @return
*/
public static Element element(String xml, String... nodes) {
try {
Document document = DocumentHelper.parseText(xml);
Element element = document.getRootElement();
for (String node : nodes) {
element = element.element(node);
}
return element;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
public class Main {
public static void main(String[] args) {
String xmlString = "Harry Potter ";
// 获取 books 元素
Element booksElement = element(xmlString);
System.out.println("Books: " + booksElement.asXML());
// 获取 category 元素
Element categoryElement = element(xmlString, "category");
System.out.println("Category: " + categoryElement.asXML());
// 获取 book 元素
Element bookElement = element(xmlString, "category", "book");
System.out.println("Book: " + bookElement.asXML());
}
// 之前的 element 函数
public static Element element(String xml, String... nodes) {
// ...
}
}
Books: <books><category name="Fiction"><book id="1">Harry Potter</book></category></books>
Category: <category name="Fiction"><book id="1">Harry Potter</book></category>
Book: <book id="1">Harry Potter</book>