Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright 2009 Tomas Varaneckas 
 * http://www.varaneckas.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Gets the long value of an attribute in given XML
     * 
     * @see #getAttribute(String, String, String)
     * @param inputXml Source XML
     * @param tag Tag name
     * @param attribute Attribute name
     * @return Value of the attribute parsed as long
     */
    public static long getLongAttribute(final String inputXml, final String tag, final String attribute) {
        return Long.parseLong(getAttribute(inputXml, tag, attribute));
    }

    /**
     * Gets the value of a tag attribute
     * 
     * @param inputXml Source XML to look the tag for
     * @param tag Tag name
     * @param attribute Attribute name
     * @return Value of the attribute
     */
    public static String getAttribute(final String inputXml, final String tag, final String attribute) {
        final String tagStart = "<".concat(tag).concat(" ");
        final int start = inputXml.indexOf(tagStart) + tagStart.length();
        final int end = inputXml.indexOf('>', start);
        return getAttributeInRange(inputXml, attribute, start, end);
    }

    /**
     * Looks for attribute value in XML String within a given range 
     * 
     * @param inputXml Source XML String
     * @param attribute Attribute name
     * @param start Range start
     * @param end Range end
     * @return Value of the attribute
     */
    private static String getAttributeInRange(final String inputXml, final String attribute, int start, int end) {
        final String attributes = inputXml.substring(start, end).trim();
        start = attributes.indexOf(attribute.concat("="));
        if (start == -1) {
            return null;
        }
        start += attribute.length() + 1;
        final char quote = attributes.charAt(start);
        start++;
        end = attributes.indexOf(quote, start);
        return attributes.substring(start, end);
    }
}