~vcs-imports/xena/trunk

« back to all changes in this revision

Viewing changes to ext/src/xalan-j_2_7_1/samples/ApplyXPath/ApplyXPath.java

  • Committer: matthewoliver
  • Date: 2009-12-10 03:18:07 UTC
  • Revision ID: vcs-imports@canonical.com-20091210031807-l086qguzdlljtkl9
Merged Xena Testing into Xena Stable for the Xena 5 release.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Licensed to the Apache Software Foundation (ASF) under one
 
3
 * or more contributor license agreements. See the NOTICE file
 
4
 * distributed with this work for additional information
 
5
 * regarding copyright ownership. The ASF licenses this file
 
6
 * to you under the Apache License, Version 2.0 (the  "License");
 
7
 * you may not use this file except in compliance with the License.
 
8
 * You may obtain a copy of the License at
 
9
 *
 
10
 *     http://www.apache.org/licenses/LICENSE-2.0
 
11
 *
 
12
 * Unless required by applicable law or agreed to in writing, software
 
13
 * distributed under the License is distributed on an "AS IS" BASIS,
 
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
15
 * See the License for the specific language governing permissions and
 
16
 * limitations under the License.
 
17
 */
 
18
/*
 
19
 * $Id: ApplyXPath.java,v 1.2 2009/12/10 03:18:42 matthewoliver Exp $
 
20
 */
 
21
// This file uses 4 space indents, no tabs.
 
22
 
 
23
import java.io.FileInputStream;
 
24
import java.io.OutputStreamWriter;
 
25
 
 
26
import javax.xml.parsers.DocumentBuilderFactory;
 
27
import javax.xml.transform.OutputKeys;
 
28
import javax.xml.transform.Transformer;
 
29
import javax.xml.transform.TransformerFactory;
 
30
import javax.xml.transform.dom.DOMSource;
 
31
import javax.xml.transform.stream.StreamResult;
 
32
 
 
33
import org.apache.xpath.XPathAPI;
 
34
import org.w3c.dom.Document;
 
35
import org.w3c.dom.Node;
 
36
import org.w3c.dom.traversal.NodeIterator;
 
37
import org.xml.sax.InputSource;
 
38
 
 
39
/**
 
40
 *  Very basic utility for applying an XPath epxression to an xml file and printing information
 
41
 /  about the execution of the XPath object and the nodes it finds.
 
42
 *  Takes 2 arguments:
 
43
 *     (1) an xml filename
 
44
 *     (2) an XPath expression to apply to the file
 
45
 *  Examples:
 
46
 *     java ApplyXPath foo.xml /
 
47
 *     java ApplyXPath foo.xml /doc/name[1]/@last
 
48
 * @see XPathAPI
 
49
 */
 
50
public class ApplyXPath
 
51
{
 
52
  protected String filename = null;
 
53
  protected String xpath = null;
 
54
 
 
55
  /** Process input args and execute the XPath.  */
 
56
  public void doMain(String[] args)
 
57
    throws Exception
 
58
  {
 
59
    filename = args[0];
 
60
    xpath = args[1];
 
61
 
 
62
    if ((filename != null) && (filename.length() > 0)
 
63
        && (xpath != null) && (xpath.length() > 0))
 
64
    {
 
65
      // Tell that we're loading classes and parsing, so the time it 
 
66
      // takes to do this doesn't get confused with the time to do 
 
67
      // the actual query and serialization.
 
68
      System.out.println("Loading classes, parsing "+filename+", and setting up serializer");
 
69
      
 
70
      // Set up a DOM tree to query.
 
71
      InputSource in = new InputSource(new FileInputStream(filename));
 
72
      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
 
73
      dfactory.setNamespaceAware(true);
 
74
      Document doc = dfactory.newDocumentBuilder().parse(in);
 
75
      
 
76
      // Set up an identity transformer to use as serializer.
 
77
      Transformer serializer = TransformerFactory.newInstance().newTransformer();
 
78
      serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 
79
 
 
80
      // Use the simple XPath API to select a nodeIterator.
 
81
      System.out.println("Querying DOM using "+xpath);
 
82
      NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath);
 
83
 
 
84
      // Serialize the found nodes to System.out.
 
85
      System.out.println("<output>");
 
86
                  
 
87
      Node n;
 
88
      while ((n = nl.nextNode())!= null)
 
89
      {         
 
90
        if (isTextNode(n)) {
 
91
            // DOM may have more than one node corresponding to a 
 
92
            // single XPath text node.  Coalesce all contiguous text nodes
 
93
            // at this level
 
94
            StringBuffer sb = new StringBuffer(n.getNodeValue());
 
95
            for (
 
96
              Node nn = n.getNextSibling(); 
 
97
              isTextNode(nn);
 
98
              nn = nn.getNextSibling()
 
99
            ) {
 
100
              sb.append(nn.getNodeValue());
 
101
            }
 
102
            System.out.print(sb);
 
103
        }
 
104
        else {
 
105
         serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
 
106
        }
 
107
        System.out.println();
 
108
      }
 
109
      System.out.println("</output>");
 
110
    }
 
111
    else
 
112
    {
 
113
      System.out.println("Bad input args: " + filename + ", " + xpath);
 
114
    }
 
115
  }
 
116
  
 
117
  /** Decide if the node is text, and so must be handled specially */
 
118
  static boolean isTextNode(Node n) {
 
119
    if (n == null)
 
120
      return false;
 
121
    short nodeType = n.getNodeType();
 
122
    return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE;
 
123
  }
 
124
 
 
125
  /** Main method to run from the command line.    */
 
126
  public static void main (String[] args)
 
127
    throws Exception
 
128
  {
 
129
    if (args.length != 2)
 
130
    {
 
131
      System.out.println("java ApplyXPath filename.xml xpath\n"
 
132
                         + "Reads filename.xml and applies the xpath; prints the nodelist found.");
 
133
      return;
 
134
    }
 
135
        
 
136
    ApplyXPath app = new ApplyXPath();
 
137
    app.doMain(args);
 
138
  }     
 
139
  
 
140
} // end of class ApplyXPath
 
141