List of usage examples for org.w3c.dom.traversal NodeFilter NodeFilter
NodeFilter
From source file:DOMTreeWalkerTreeModel.java
/** * This main() method demonstrates the use of this class, the use of the * Xerces DOM parser, and the creation of a DOM Level 2 TreeWalker object. *///from w w w . j av a 2 s.c om public static void main(String[] args) throws IOException, SAXException { // Obtain an instance of a Xerces parser to build a DOM tree. // Note that we are not using the JAXP API here, so this // code uses Apache Xerces APIs that are not standards DOMParser parser = new org.apache.xerces.parsers.DOMParser(); // Get a java.io.Reader for the input XML file and // wrap the input file in a SAX input source Reader in = new BufferedReader(new FileReader(args[0])); InputSource input = new org.xml.sax.InputSource(in); // Tell the Xerces parser to parse the input source parser.parse(input); // Ask the parser to give us our DOM Document. Once we've got the DOM // tree, we don't have to use the Apache Xerces APIs any more; from // here on, we use the standard DOM APIs Document document = parser.getDocument(); // If we're using a DOM Level 2 implementation, then our Document // object ought to implement DocumentTraversal DocumentTraversal traversal = (DocumentTraversal) document; // For this demonstration, we create a NodeFilter that filters out // Text nodes containing only space; these just clutter up the tree NodeFilter filter = new NodeFilter() { public short acceptNode(Node n) { if (n.getNodeType() == Node.TEXT_NODE) { // Use trim() to strip off leading and trailing space. // If nothing is left, then reject the node if (((Text) n).getData().trim().length() == 0) return NodeFilter.FILTER_REJECT; } return NodeFilter.FILTER_ACCEPT; } }; // This set of flags says to "show" all node types except comments int whatToShow = NodeFilter.SHOW_ALL & ~NodeFilter.SHOW_COMMENT; // Create a TreeWalker using the filter and the flags TreeWalker walker = traversal.createTreeWalker(document, whatToShow, filter, false); // Instantiate a TreeModel and a JTree to display it JTree tree = new JTree(new DOMTreeWalkerTreeModel(walker)); // Create a frame and a scrollpane to display the tree, and pop them up JFrame frame = new JFrame("DOMTreeWalkerTreeModel Demo"); frame.getContentPane().add(new JScrollPane(tree)); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setSize(500, 250); frame.setVisible(true); }
From source file:de.betterform.xml.dom.DOMUtil.java
/** * copies all attributes from one Element to another * * @param from - the Element which the source attributes * @param to - the target Element for the Attributes * @param filter - a NodeFilter to apply during copy *//*from w w w . j a v a2 s . c om*/ public static void copyAttributes(Element from, Element to, NodeFilter filter) { if ((from != null) && (to != null)) { NamedNodeMap map = from.getAttributes(); /* if filter is null use our own default filter, which accepts everything (this saves us from always check if filter is null */ if (filter == null) { filter = new NodeFilter() { public short acceptNode(Node n) { return NodeFilter.FILTER_ACCEPT; } }; } if (map != null) { int len = map.getLength(); for (int i = 0; i < len; i++) { Node attr = map.item(i); if (attr.getNodeType() == Node.ATTRIBUTE_NODE) { if (filter.acceptNode(attr) == NodeFilter.FILTER_ACCEPT) { to.setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(), attr.getNodeValue()); } } } } } }
From source file:eu.semaine.util.XMLTool.java
/** * Create a node iterator for the current document, which will provide exactly * the elements below root in the given namespace whose local names are in localNames. * This is independent of any namespace prefixes. * @param doc/*from w ww . j av a 2 s. com*/ * @param root * @param namespaceURI * @param localNames the array of local names to be accepted. * @return */ public static NodeIterator createNodeIterator(Document doc, Node root, final String namespaceURI, final String... localNames) { NodeIterator ni = ((DocumentTraversal) doc).createNodeIterator(root, NodeFilter.SHOW_ELEMENT, new NodeFilter() { @Override public short acceptNode(Node n) { if (!isSameNamespace(n.getNamespaceURI(), namespaceURI)) { return NodeFilter.FILTER_SKIP; } for (String localName : localNames) { if (localName.equals(n.getLocalName())) { return NodeFilter.FILTER_ACCEPT; } } return NodeFilter.FILTER_SKIP; } }, false); return ni; }
From source file:org.alfresco.repo.template.XSLTProcessorMethodInvoker.java
public Object invokeMethod(final String id, Object[] arguments) throws Exception { if (!PROCESSOR_METHODS.containsKey(id)) { throw new NullPointerException("unable to find method " + id); }/*from www .ja va 2 s . c o m*/ final TemplateProcessorMethod method = PROCESSOR_METHODS.get(id); arguments = this.convertArguments(arguments); log.debug("invoking " + id + " with " + arguments.length); Object result = method.exec(arguments); log.debug(id + " returned a " + result); if (result == null) { return null; } else if (result.getClass().isArray() && Node.class.isAssignableFrom(result.getClass().getComponentType())) { log.debug("converting " + result + " to a node iterator"); final Node[] array = (Node[]) result; return new NodeIterator() { private int index = 0; private boolean detached = false; public void detach() { if (log.isDebugEnabled()) log.debug("detaching NodeIterator"); this.detached = true; } public boolean getExpandEntityReferences() { return true; } public int getWhatToShow() { return NodeFilter.SHOW_ALL; } public Node getRoot() { return (array.length == 0 ? null : array[0].getOwnerDocument().getDocumentElement()); } public NodeFilter getFilter() { return new NodeFilter() { public short acceptNode(final Node n) { return NodeFilter.FILTER_ACCEPT; } }; } public Node nextNode() throws DOMException { if (log.isDebugEnabled()) log.debug("NodeIterator.nextNode(" + index + ")"); if (this.detached) throw new DOMException(DOMException.INVALID_STATE_ERR, null); return index == array.length ? null : array[index++]; } public Node previousNode() throws DOMException { if (log.isDebugEnabled()) log.debug("NodeIterator.previousNode(" + index + ")"); if (this.detached) throw new DOMException(DOMException.INVALID_STATE_ERR, null); return index == -1 ? null : array[index--]; } }; } else if (result instanceof String || result instanceof Number || result instanceof Node) { log.debug("returning " + result + " as is"); return result; } else { throw new IllegalArgumentException("unable to convert " + result.getClass().getName()); } }
From source file:org.apache.any23.extractor.microdata.MicrodataParser.java
/** * Returns all the <b>itemprop</b>s for the given <b>itemscope</b> node. * * @param scopeNode node representing the <b>itemscope</b> * @param skipRoot if <code>true</code> the given root <code>node</code> * will be not read as a property, even if it contains the <b>itemprop</b> attribute. * @return the list of <b>itemprop</b>s detected within the given <b>itemscope</b>. * @throws MicrodataParserException if an error occurs while retrieving an property value. *//*from w w w.jav a 2 s .co m*/ public List<ItemProp> getItemProps(final Node scopeNode, boolean skipRoot) throws MicrodataParserException { final Set<Node> accepted = new LinkedHashSet<>(); if (!skipRoot) { NamedNodeMap attributes = scopeNode.getAttributes(); if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null) { accepted.add(scopeNode); } } // TreeWalker to walk DOM tree starting with the scopeNode. Nodes maybe visited multiple times. TreeWalker treeWalker = ((DocumentTraversal) scopeNode.getOwnerDocument()).createTreeWalker(scopeNode, NodeFilter.SHOW_ELEMENT, new NodeFilter() { @Override public short acceptNode(Node node) { if (node.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap attributes = node.getAttributes(); if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null && !scopeNode.equals(node)) { accepted.add(node); } if (attributes.getNamedItem(ITEMSCOPE_ATTRIBUTE) != null) { // Don't visit descendants of nodes that define a new scope return FILTER_REJECT; } } return FILTER_ACCEPT; } }, false); // To populate accepted we only need to walk the tree. while (treeWalker.nextNode() != null) ; final List<ItemProp> result = new ArrayList<>(); for (Node itemPropNode : accepted) { final String itemProp = DomUtils.readAttribute(itemPropNode, ITEMPROP_ATTRIBUTE, null); if (StringUtils.isBlank(itemProp)) { manageError(new MicrodataParserException("invalid property name '" + itemProp + "'", itemPropNode)); continue; } final String[] propertyNames = itemProp.trim().split("\\s+"); ItemPropValue itemPropValue; for (String propertyName : propertyNames) { try { itemPropValue = getPropertyValue(itemPropNode); } catch (MicrodataParserException mpe) { manageError(mpe); continue; } result.add(new ItemProp(DomUtils.getXPathForNode(itemPropNode), propertyName, itemPropValue)); } } return result; }