【问题标题】:JAVA XML, find recursivelyJAVA XML,递归查找
【发布时间】:2012-07-17 17:46:42
【问题描述】:

我需要通过 id 递归查找 xml 节点,如下所示:

<categories>
  <category id="1">
  </category>
  <category id="2">
     <category id="3"> 
     </category>
     <category id="4"> 
        <category id="5"> 
        </category> 
     </category>
  </category>
</categories>

我正在使用 DocBuilder。

我知道有 getElementById() 方法,但它在我的情况下不起作用,比如说,当我在根节点中时,我想找到一个带有 id="5" 的元素。

有可能吗?

【问题讨论】:

  • getElementById() 搜索整个文档,而不仅仅是元素的子节点。如果您有一个指定属性为xml:id 的模式,它应该做您想做的事。 (见这个问题:stackoverflow.com/questions/3423430/…)

标签: java xml


【解决方案1】:

用根节点调用方法:

Element element = getElementById(rootElement, "5");

还有递归方法:

public Element getElementById(Element element, String desiredId){
    if(desiredId.equals(element.getAttribute("id")))
        return element;
    for(int i=0; i < element.getChildNodes().getLength(); i++){
        Node node = element.getChildNodes().item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE){
            Element child = getElementById((Element) node, desiredId);
            if(child != null)
                return child;
        }
    }
    return null;
}

【讨论】:

  • 但是这种方法并不完全递归......它不会比第一个孩子更深......
【解决方案2】:

为什么不直接做下面的伪代码

FindChild(parent, id)
{

    if(parent.getChildById(id)) return parent.getChildById(id);

    foreach(parent.child)
    {
         Element found = FindChild(child, id);
         if(found) return found;
    }

    return NULL;
}

如果具有指定 id 的元素出现在层次结构中的多个位置(即返回第一次出现或构建列表),您必须决定该怎么做

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2017-01-19
    相关资源
    最近更新 更多