[英]dom4j-java- how to get all elements (parent or children) within root that have specific element name
我想獲取xml中的元素數量,這些元素具有特定的名稱,例如。 名稱=“同時”)
問題是,如果我使用以下代碼 - 我只獲得具有此名稱的頂級元素 -
for ( Iterator i = root.elementIterator( "while" ); i.hasNext(); ) {
Element foo = (Element) i.next();
但任何較低級別的“while”元素都不是迭代器的一部分......
獲得name =“while”的所有元素(無論是頂級還是低級)的最有效方法是什么? 為此,我是否必須解析文檔中的所有元素?
您可以使用//while
來使用//while
或name()
函數和通配符節點*
: //*[name() = 'while']
List list = document.selectNodes("//*[name() = 'while']"); // or "//while"
int numberOfNodes = list.size();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
// do something
}
這個正則表達式對我有用:
document.selectNodes(".//*")
Element Iterator僅適用於xPath中的下一級。 為了能夠解析所有XML並獲取所有Element,您必須使用一些遞歸。 例如,下一個代碼將返回具有“名稱”的所有節點的列表
public List<Element> getElementsByName(String name, Element parent, List<Element> elementList)
{
if (elementList == null)
elementList = new ArrayList<Element>();
for ( Iterator i = parent.elementIterator(); i.hasNext(); ) {
Element current = (Element) i.next();
if (current.getName().equalsIgnoreCase(name))
{
elementList.add(current);
}
getElementsByName(name, current, elementList);
}
return elementList;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.