Shallow print of node list : XPath « XML « Java






Shallow print of node list

    
import java.io.OutputStream;
import java.io.PrintStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

import com.sun.org.apache.xpath.internal.XPathAPI;

public class MainClass {
  public static void print(Node node, OutputStream os) {
    PrintStream ps = new PrintStream(os);
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      ps.print("<" + node.getNodeName());

      NamedNodeMap map = node.getAttributes();
      for (int i = 0; i < map.getLength(); i++) {
        ps.print(" " + map.item(i).getNodeName() + "=\""
            + map.item(i).getNodeValue() + "\"");
      }
      ps.println(">");
      return;
    case Node.ATTRIBUTE_NODE:
      ps.println(node.getNodeName() + "=\"" + node.getNodeValue() + "\"");
      return;
    case Node.TEXT_NODE:
      ps.println(node.getNodeValue());
      return;
    case Node.CDATA_SECTION_NODE:
      ps.println(node.getNodeValue());
      return;
    case Node.PROCESSING_INSTRUCTION_NODE:
      ps.println(node.getNodeValue());
      return;
    case Node.DOCUMENT_NODE:
    case Node.DOCUMENT_FRAGMENT_NODE:
      ps.println(node.getNodeName() + "=" + node.getNodeValue());
      return;
    }
  }

  static void evalXPath(Document doc, Transformer serializer, String absolute,
      String relative) throws Exception {
    NodeList list = XPathAPI.selectNodeList(doc, absolute, doc);
    Node node = null;
    // 
    for (int i = 0; (node = list.item(i)) != null; i++) {
      NodeList innerList = XPathAPI.selectNodeList(node, relative, doc);
      Node innerNode = null;
      for (int j = 0; (innerNode = innerList.item(j)) != null; j++) {
        print(innerNode, System.out);
      }
    }
  }
}

   
    
    
  








Related examples in the same category

1.Create an XML document and search by XPath
2.Use XPath to select node
3.Deep print of node list
4.Parse with XPath
5.XML and XPath utilities
6.Get the String data associated with the XPath selection supplied
7.This program evaluates XPath expressions