工具类:
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 = "<books><category name='Fiction'><book id='1'>Harry Potter</book></category></books>";Element booksElement = element(xmlString);System.out.println("Books: " + booksElement.asXML());Element categoryElement = element(xmlString, "category");System.out.println("Category: " + categoryElement.asXML());Element bookElement = element(xmlString, "category", "book");System.out.println("Book: " + bookElement.asXML());}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>