Java 怎么从给定的父节点获取具有指定名称的第一个子XML元素

2019年8月6日22:16:40Java 怎么从给定的父节点获取具有指定名称的第一个子XML元素已关闭评论 469 1114字阅读3分42秒

1.简介

Java 怎么从给定的父节点获取具有指定名称的第一个子XML元素?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

   Copyright (C) 2016 HermeneutiX.org

   This file is part of SciToS.

   SciToS is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   SciToS is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with SciToS. If not, see <http:
 */


import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    
    public static Element getChildElement(final Node parentNode,
            final String childNodeName) {
        final NodeList candidates = parentNode.getChildNodes();
        final int childCount = candidates.getLength();
        for (int childIndex = 0; childIndex < childCount; childIndex++) {
            final Node singleChild = candidates.item(childIndex);
            if (singleChild instanceof Element
                    && childNodeName.equals(((Element) singleChild)
                            .getTagName())) {
                
                return (Element) singleChild;
            }
        }
        return null;
    }
}

 
继续阅读
编程十万个怎么办