001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements. See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership. The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the  "License");
007     * you may not use this file except in compliance with the License.
008     * You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    /*
019     * $Id: ExsltBase.java 468639 2006-10-28 06:52:33Z minchau $
020     */
021    package org.apache.xalan.lib;
022    
023    import org.apache.xml.dtm.ref.DTMNodeProxy;
024    
025    import org.w3c.dom.Node;
026    import org.w3c.dom.NodeList;
027    
028    /**
029     * The base class for some EXSLT extension classes.
030     * It contains common utility methods to be used by the sub-classes.
031     */
032    public abstract class ExsltBase
033    {
034      /**
035       * Return the string value of a Node
036       *
037       * @param n The Node.
038       * @return The string value of the Node
039       */
040      protected static String toString(Node n)
041      {
042        if (n instanceof DTMNodeProxy)
043             return ((DTMNodeProxy)n).getStringValue();
044        else
045        {
046          String value = n.getNodeValue();
047          if (value == null)
048          {
049            NodeList nodelist = n.getChildNodes();
050            StringBuffer buf = new StringBuffer();
051            for (int i = 0; i < nodelist.getLength(); i++)
052            {
053              Node childNode = nodelist.item(i);
054              buf.append(toString(childNode));
055            }
056            return buf.toString();
057          }
058          else
059            return value;
060        }
061      }
062      
063      /**
064       * Convert the string value of a Node to a number.
065       * Return NaN if the string is not a valid number.
066       *
067       * @param n The Node.
068       * @return The number value of the Node
069       */
070      protected static double toNumber(Node n)
071      {
072        double d = 0.0;
073        String str = toString(n);
074        try
075        {
076          d = Double.valueOf(str).doubleValue();
077        }
078        catch (NumberFormatException e)
079        {
080          d= Double.NaN;            
081        }
082        return d;
083      }
084    }