Gets the version of the XML. - Java XML

Java examples for XML:XML Declaration

Description

Gets the version of the XML.

Demo Code

/*/*  ww  w . ja va  2  s. c o  m*/
 * Copyright 2015 Andrej_Petras.
 *
 * 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.
 */
//package com.java2s;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class Main {
    /**
     * Gets the version of the XML.
     *
     * @param path the XML file.
     * @return the corresponding version of the XML.
     */
    public static String getXMLVersion(final Path path) {
        try (InputStream inputStream = Files.newInputStream(path)) {
            XMLStreamReader reader = XMLInputFactory.newInstance()
                    .createXMLStreamReader(inputStream);
            for (int event; (event = reader.next()) != XMLStreamConstants.END_DOCUMENT;) {
                if (event == XMLStreamConstants.START_ELEMENT) {
                    String tmp = reader.getLocalName();
                    if ("persistence".equals(tmp)) {
                        for (int i = 0; i < reader.getAttributeCount(); i++) {
                            if ("version".equals(reader.getAttributeName(i)
                                    .toString())) {
                                return reader.getAttributeValue(i);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException(
                    "Error reading the persistence.xml version.", ex);
        }
        return null;
    }
}

Related Tutorials