Thursday 4 August 2011

Getting a Node Relative to Another Node in a DOM Document

      

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

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

public class Main {
  public static void main(String[] argvthrows Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);

    factory.setExpandEntityReferences(false);

    Document doc1 = factory.newDocumentBuilder().parse(new File("filename"));
    NodeList list = doc1.getElementsByTagName("entry");
    Element element = (Elementlist.item(0);

    Document doc2 = factory.newDocumentBuilder().parse(new File("infilename2.xml"));

    // Make a copy of the element subtree suitable for inserting into doc2
    Node node = doc2.importNode(element, true);

    // Get the parent
    Node parent = node.getParentNode();

    // Get children
    NodeList children = node.getChildNodes();

    // Get first child; null if no children
    Node child = node.getFirstChild();

    // Get last child; null if no children
    child = node.getLastChild();

    // Get next sibling; null if node is last child
    Node sibling = node.getNextSibling();

    // Get previous sibling; null if node is first child
    sibling = node.getPreviousSibling();

    // Get first sibling
    sibling = node.getParentNode().getFirstChild();

    // Get last sibling
    sibling = node.getParentNode().getLastChild();

  }
}

   
    
    
    
    
    
  

No comments:

Post a Comment