Java tutorial
//package com.java2s; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.Set; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Node; public class Main { /** * This method returns the owner document of a particular node. * This method is necessary because it <I>always</I> returns a * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE> * if the {@link Node} is a {@link Document}. * * @param node * @return the owner document of the node */ public static Document getOwnerDocument(Node node) { if (node.getNodeType() == Node.DOCUMENT_NODE) { return (Document) node; } try { return node.getOwnerDocument(); } catch (NullPointerException npe) { throw new NullPointerException(npe.getMessage()); } } /** * This method returns the first non-null owner document of the Nodes in this Set. * This method is necessary because it <I>always</I> returns a * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE> * if the {@link Node} is a {@link Document}. * * @param xpathNodeSet * @return the owner document */ public static Document getOwnerDocument(Set<Node> xpathNodeSet) { NullPointerException npe = null; for (Node node : xpathNodeSet) { int nodeType = node.getNodeType(); if (nodeType == Node.DOCUMENT_NODE) { return (Document) node; } try { if (nodeType == Node.ATTRIBUTE_NODE) { return ((Attr) node).getOwnerElement().getOwnerDocument(); } return node.getOwnerDocument(); } catch (NullPointerException e) { npe = e; } } throw new NullPointerException(npe.getMessage()); } }