yangdd1205 2014-01-03 07:30 采纳率: 100%
浏览 7447
已结题

dom4j中能否通过节点的属性获得某个具体的节点?

<root>
<node name="a">
    <xml>1</xml>
</node>
<node name="b">
    <xml>2</xml>
</node>
<node name="c">
    <xml>3</xml>
</node>
    ....

我想获得 node name="b" 的这个节点该怎么办?求各位大神帮忙解决下!!

  • 写回答

1条回答 默认 最新

  • epw1315620 2014-01-03 18:07
    关注
    public static void main(String[] args) {
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = saxReader.read(new File(Dom4j.class.getClass()
                    .getResource("/").getFile().toString()
                    + "test.xml"));
            Element root = document.getRootElement();
            Element node = Dom4j.parse(root , "name" , "b");
            ...
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /*
     * 获得X属性结果是X值的整个标签
     */
    public static Element parse(Element node , String type , String val) {
        for (Iterator iter = node.elementIterator(); iter.hasNext();) {
            Element element = (Element) iter.next();
            Attribute name = element.attribute(type);
            if (name != null) {
                String value = name.getValue();
                if (value != null && val.equals(value))
                    return element;
                else
                    parse(element , type , val);
            }
        }
        return null;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile