工具类:
java
/**
* 根据标签名递归读取xml字符串中element
* 例:
* String xml =
* "<req>\n" +
* "<tag1></tag1>\n" +
* "<tag2>\n" +
* " <tag4></tag4>\n" +
* "</tag2>\n" +
* "<tag3></tag3>\n" +
* "</req>";
* <p>
* 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;
}
测试:
java
public class Main {
public static void main(String[] args) {
String xmlString = "<books><category name='Fiction'><book id='1'>Harry Potter</book></category></books>";
// 获取 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) {
// ...
}
}
输出:
java
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>