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

2019年8月6日22:16:38Java 怎么从给定的父节点获取具有指定名称的所有子XML元素已关闭评论 431 1355字阅读4分31秒

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 java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

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

public class Main {
    
    public static List<Element> getChildElements(final Node parentNode,
            final String... childNodeNames) {
        final List<Element> children = new LinkedList<Element>();
        final NodeList candidates = parentNode.getChildNodes();
        final int childCount = candidates.getLength();
        final List<String> targetNodeNames = Arrays.asList(childNodeNames);
        for (int childIndex = 0; childIndex < childCount; childIndex++) {
            final Node singleChild = candidates.item(childIndex);
            if (singleChild instanceof Element
                    && (targetNodeNames.isEmpty() || targetNodeNames
                            .contains(((Element) singleChild).getTagName()))) {
                children.add((Element) singleChild);
            }
        }
        return children;
    }
}

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