~ubuntu-branches/ubuntu/saucy/libxalan2-java/saucy-security

« back to all changes in this revision

Viewing changes to samples/XPathAPI/ApplyXPathJAXP.java

  • Committer: Bazaar Package Importer
  • Author(s): Michael Koch
  • Date: 2008-04-27 10:20:03 UTC
  • mfrom: (1.1.3 upstream) (3.1.11 hardy)
  • Revision ID: james.westby@ubuntu.com-20080427102003-qy06c2if0qayzwlg
Tags: 2.7.1-2
* Build-Depends on default-jdk-builddep. Closes: #477893
* Clarified debian/copyright.
* Don't use '-1' in Build-Depends.
* Updated watch file to match upstream correctly.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * Copyright 2001-2004 The Apache Software Foundation.
3
 
 *
4
 
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 
 * you may not use this file except in compliance with the License.
6
 
 * You may obtain a copy of the License at
7
 
 *
8
 
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 
 *
10
 
 * Unless required by applicable law or agreed to in writing, software
11
 
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 
 * See the License for the specific language governing permissions and
14
 
 * limitations under the License.
15
 
 */
16
 
 
17
 
import java.io.OutputStreamWriter;
18
 
 
19
 
import javax.xml.namespace.*;
20
 
import javax.xml.transform.*;
21
 
import javax.xml.transform.dom.DOMSource;
22
 
import javax.xml.transform.stream.StreamResult;
23
 
import javax.xml.xpath.*;
24
 
import org.xml.sax.*;
25
 
import org.w3c.dom.*;
26
 
 
27
 
/**
28
 
 * JAXP 1.3 XPath API sample.
29
 
 * 
30
 
 * Basic utility for applying an XPath expression to an input xml file and printing
31
 
 * the evaluation result, using JAXP 1.3 XPath API.
32
 
 * 
33
 
 * Takes 3 arguments:
34
 
 * (1) an xml file name
35
 
 * (2) an XPath expression to apply to the input document
36
 
 * (3) the return type, which is one of the following Strings:
37
 
 *     num, bool, str, node, nodeset
38
 
 * 
39
 
 * Examples:
40
 
 *      java ApplyXPathJAXP foo.xml /doc/name[1]/@last str
41
 
 *      java ApplyXPathJAXP foo.xml /doc/name nodeset
42
 
 */
43
 
public class ApplyXPathJAXP
44
 
{
45
 
    public static void main(String[] args)
46
 
    {
47
 
        QName returnType = null;
48
 
        
49
 
        if (args.length != 3)
50
 
        {
51
 
            System.err.println("Usage: java ApplyXPathAPI xml_file xpath_expression type");
52
 
        }
53
 
        
54
 
        InputSource xml = new InputSource(args[0]);
55
 
        String expr = args[1];
56
 
        
57
 
        // set the return type
58
 
        if (args[2].equals("num")) returnType = XPathConstants.NUMBER;
59
 
        else if (args[2].equals("bool")) returnType = XPathConstants.BOOLEAN;
60
 
        else if (args[2].equals("str")) returnType = XPathConstants.STRING;
61
 
        else if (args[2].equals("node")) returnType = XPathConstants.NODE;
62
 
        else if (args[2].equals("nodeset")) returnType = XPathConstants.NODESET;
63
 
        else
64
 
          System.err.println("Invalid return type: " + args[2]);
65
 
        
66
 
        // Create a new XPath
67
 
        XPathFactory factory = XPathFactory.newInstance();
68
 
        XPath xpath = factory.newXPath();
69
 
        
70
 
        Object result = null;
71
 
        try {
72
 
          // compile the XPath expression
73
 
          XPathExpression xpathExpr = xpath.compile(expr);
74
 
          
75
 
          // Evaluate the XPath expression against the input document
76
 
          result = xpathExpr.evaluate(xml, returnType);
77
 
          
78
 
          // Print the result to System.out.
79
 
          printResult(result);
80
 
        }
81
 
        catch (Exception e) {
82
 
          e.printStackTrace();
83
 
        }        
84
 
    }
85
 
    
86
 
    /**
87
 
     * Print the type and value of the evaluation result.
88
 
     */
89
 
    static void printResult(Object result)
90
 
      throws Exception
91
 
    {
92
 
        if (result instanceof Double) {
93
 
            System.out.println("Result type: double");
94
 
            System.out.println("Value: " + result);
95
 
        }
96
 
        else if (result instanceof Boolean) {
97
 
            System.out.println("Result type: boolean");
98
 
            System.out.println("Value: " + ((Boolean)result).booleanValue());
99
 
        }       
100
 
        else if (result instanceof String) {
101
 
            System.out.println("Result type: String");
102
 
             System.out.println("Value: " + result);
103
 
        }
104
 
        else if (result instanceof Node) {
105
 
            Node node = (Node)result;
106
 
            System.out.println("Result type: Node");
107
 
            System.out.println("<output>");
108
 
            printNode(node);
109
 
            System.out.println("</output>");
110
 
        }
111
 
        else if (result instanceof NodeList) {
112
 
            NodeList nodelist = (NodeList)result;
113
 
            System.out.println("Result type: NodeList");
114
 
            System.out.println("<output>");
115
 
            printNodeList(nodelist);
116
 
            System.out.println("</output>");
117
 
        }
118
 
    }
119
 
 
120
 
    /** Decide if the node is text, and so must be handled specially */
121
 
    static boolean isTextNode(Node n) 
122
 
    {
123
 
      if (n == null)
124
 
        return false;
125
 
      short nodeType = n.getNodeType();
126
 
      return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE;
127
 
    }
128
 
    
129
 
    static void printNode(Node node) 
130
 
      throws Exception
131
 
    {
132
 
      if (isTextNode(node)) {
133
 
        System.out.println(node.getNodeValue());       
134
 
      }
135
 
      else {
136
 
        // Set up an identity transformer to use as serializer.
137
 
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
138
 
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
139
 
        serializer.transform(new DOMSource(node), new StreamResult(new OutputStreamWriter(System.out)));
140
 
      }        
141
 
       
142
 
    }
143
 
    
144
 
    static void printNodeList(NodeList nodelist) 
145
 
      throws Exception
146
 
    {
147
 
      Node n;
148
 
      
149
 
      // Set up an identity transformer to use as serializer.
150
 
      Transformer serializer = TransformerFactory.newInstance().newTransformer();
151
 
      serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
152
 
      
153
 
      for (int i = 0; i < nodelist.getLength(); i++)
154
 
      {         
155
 
        n = nodelist.item(i);
156
 
        if (isTextNode(n)) {
157
 
            // DOM may have more than one node corresponding to a 
158
 
            // single XPath text node.  Coalesce all contiguous text nodes
159
 
            // at this level
160
 
            StringBuffer sb = new StringBuffer(n.getNodeValue());
161
 
            for (
162
 
              Node nn = n.getNextSibling(); 
163
 
              isTextNode(nn);
164
 
              nn = nn.getNextSibling()
165
 
            ) {
166
 
              sb.append(nn.getNodeValue());
167
 
            }
168
 
            System.out.print(sb);
169
 
        }
170
 
        else {
171
 
         serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
172
 
        }
173
 
        System.out.println();
174
 
      }
175
 
    }
176
 
}
 
 
b'\\ No newline at end of file'
 
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
import java.io.OutputStreamWriter;
 
20
 
 
21
import javax.xml.namespace.*;
 
22
import javax.xml.transform.*;
 
23
import javax.xml.transform.dom.DOMSource;
 
24
import javax.xml.transform.stream.StreamResult;
 
25
import javax.xml.xpath.*;
 
26
import org.xml.sax.*;
 
27
import org.w3c.dom.*;
 
28
 
 
29
/**
 
30
 * JAXP 1.3 XPath API sample.
 
31
 * 
 
32
 * Basic utility for applying an XPath expression to an input xml file and printing
 
33
 * the evaluation result, using JAXP 1.3 XPath API.
 
34
 * 
 
35
 * Takes 3 arguments:
 
36
 * (1) an xml file name
 
37
 * (2) an XPath expression to apply to the input document
 
38
 * (3) the return type, which is one of the following Strings:
 
39
 *     num, bool, str, node, nodeset
 
40
 * 
 
41
 * Examples:
 
42
 *      java ApplyXPathJAXP foo.xml /doc/name[1]/@last str
 
43
 *      java ApplyXPathJAXP foo.xml /doc/name nodeset
 
44
 */
 
45
public class ApplyXPathJAXP
 
46
{
 
47
    public static void main(String[] args)
 
48
    {
 
49
        QName returnType = null;
 
50
        
 
51
        if (args.length != 3)
 
52
        {
 
53
            System.err.println("Usage: java ApplyXPathAPI xml_file xpath_expression type");
 
54
        }
 
55
        
 
56
        InputSource xml = new InputSource(args[0]);
 
57
        String expr = args[1];
 
58
        
 
59
        // set the return type
 
60
        if (args[2].equals("num")) returnType = XPathConstants.NUMBER;
 
61
        else if (args[2].equals("bool")) returnType = XPathConstants.BOOLEAN;
 
62
        else if (args[2].equals("str")) returnType = XPathConstants.STRING;
 
63
        else if (args[2].equals("node")) returnType = XPathConstants.NODE;
 
64
        else if (args[2].equals("nodeset")) returnType = XPathConstants.NODESET;
 
65
        else
 
66
          System.err.println("Invalid return type: " + args[2]);
 
67
        
 
68
        // Create a new XPath
 
69
        XPathFactory factory = XPathFactory.newInstance();
 
70
        XPath xpath = factory.newXPath();
 
71
        
 
72
        Object result = null;
 
73
        try {
 
74
          // compile the XPath expression
 
75
          XPathExpression xpathExpr = xpath.compile(expr);
 
76
          
 
77
          // Evaluate the XPath expression against the input document
 
78
          result = xpathExpr.evaluate(xml, returnType);
 
79
          
 
80
          // Print the result to System.out.
 
81
          printResult(result);
 
82
        }
 
83
        catch (Exception e) {
 
84
          e.printStackTrace();
 
85
        }        
 
86
    }
 
87
    
 
88
    /**
 
89
     * Print the type and value of the evaluation result.
 
90
     */
 
91
    static void printResult(Object result)
 
92
      throws Exception
 
93
    {
 
94
        if (result instanceof Double) {
 
95
            System.out.println("Result type: double");
 
96
            System.out.println("Value: " + result);
 
97
        }
 
98
        else if (result instanceof Boolean) {
 
99
            System.out.println("Result type: boolean");
 
100
            System.out.println("Value: " + ((Boolean)result).booleanValue());
 
101
        }       
 
102
        else if (result instanceof String) {
 
103
            System.out.println("Result type: String");
 
104
             System.out.println("Value: " + result);
 
105
        }
 
106
        else if (result instanceof Node) {
 
107
            Node node = (Node)result;
 
108
            System.out.println("Result type: Node");
 
109
            System.out.println("<output>");
 
110
            printNode(node);
 
111
            System.out.println("</output>");
 
112
        }
 
113
        else if (result instanceof NodeList) {
 
114
            NodeList nodelist = (NodeList)result;
 
115
            System.out.println("Result type: NodeList");
 
116
            System.out.println("<output>");
 
117
            printNodeList(nodelist);
 
118
            System.out.println("</output>");
 
119
        }
 
120
    }
 
121
 
 
122
    /** Decide if the node is text, and so must be handled specially */
 
123
    static boolean isTextNode(Node n) 
 
124
    {
 
125
      if (n == null)
 
126
        return false;
 
127
      short nodeType = n.getNodeType();
 
128
      return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE;
 
129
    }
 
130
    
 
131
    static void printNode(Node node) 
 
132
      throws Exception
 
133
    {
 
134
      if (isTextNode(node)) {
 
135
        System.out.println(node.getNodeValue());       
 
136
      }
 
137
      else {
 
138
        // Set up an identity transformer to use as serializer.
 
139
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
 
140
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 
141
        serializer.transform(new DOMSource(node), new StreamResult(new OutputStreamWriter(System.out)));
 
142
      }        
 
143
       
 
144
    }
 
145
    
 
146
    static void printNodeList(NodeList nodelist) 
 
147
      throws Exception
 
148
    {
 
149
      Node n;
 
150
      
 
151
      // Set up an identity transformer to use as serializer.
 
152
      Transformer serializer = TransformerFactory.newInstance().newTransformer();
 
153
      serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 
154
      
 
155
      for (int i = 0; i < nodelist.getLength(); i++)
 
156
      {         
 
157
        n = nodelist.item(i);
 
158
        if (isTextNode(n)) {
 
159
            // DOM may have more than one node corresponding to a 
 
160
            // single XPath text node.  Coalesce all contiguous text nodes
 
161
            // at this level
 
162
            StringBuffer sb = new StringBuffer(n.getNodeValue());
 
163
            for (
 
164
              Node nn = n.getNextSibling(); 
 
165
              isTextNode(nn);
 
166
              nn = nn.getNextSibling()
 
167
            ) {
 
168
              sb.append(nn.getNodeValue());
 
169
            }
 
170
            System.out.print(sb);
 
171
        }
 
172
        else {
 
173
         serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
 
174
        }
 
175
        System.out.println();
 
176
      }
 
177
    }
 
178
}