Java 怎么获取XML的版本

2019年7月21日19:34:57Java 怎么获取XML的版本已关闭评论 383 893字阅读2分58秒

1.简介

Java 怎么获取XML的版本?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 

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 {
    
    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;
    }
}

 
继续阅读
编程十万个怎么办