Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.EndElement;

import javax.xml.stream.events.XMLEvent;

public class Main {
    /**
     * Get the content of this tag, assuming it's just characters with no other
     * tags beneath it. Something like <tag>This is my content</tag>
     * will return "This is my content". If there's anything but regular 
     * characters, an exception will be thrown. It also checks the end tag
     * for you. 
     * @param start The start tag
     * @param xml
     * @return The string content of this tag.
     * @throws XMLStreamException at runtime
     */
    public static String getStringContent(XMLEvent start, XMLEventReader xml) {
        String ret = "";
        XMLEvent e = nextEvent(xml);
        while (e.isCharacters()) {
            ret += e.asCharacters().getData();
            e = nextEvent(xml);
        }
        // Make sure we actually got to the end tag, not something else
        assertEnd(localNameOf(start), e);
        return ret;
    }

    /** 
     * Calls xml.nextEvent() and unchecks the exception.
     * 
     * @param xml
     * @return xml.nextEvent(), or throws a RuntimeException.
     */
    public static XMLEvent nextEvent(XMLEventReader xml) {
        try {
            return xml.nextEvent();
        } catch (XMLStreamException e) {
            throw new RuntimeException(e);
        }
    }

    public static EndElement assertEnd(String name, XMLEvent event) {
        if (!isEndTag(event, name)) {
            throw new RuntimeException("Was expecting an end tag " + name + ", not this: " + event);
        }
        return event.asEndElement();
    }

    public static String localNameOf(XMLEvent e) {
        if (e.isStartElement()) {
            return e.asStartElement().getName().getLocalPart();
        } else if (e.isEndElement()) {
            return e.asEndElement().getName().getLocalPart();
        }
        throw new RuntimeException(e + " isn't a tag to get the name of.");
    }

    public static boolean isEndTag(XMLEvent e, String localName) {
        return e.isEndElement() && localNameOf(e).equals(localName);
    }
}