Created
May 3, 2020 16:14
XMLの検証をバージョンごとに行う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URL; | |
import javax.xml.XMLConstants; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.transform.dom.DOMSource; | |
import javax.xml.validation.Schema; | |
import javax.xml.validation.SchemaFactory; | |
import org.w3c.dom.Document; | |
public class XmlChecker { | |
public static void main(String[] args) { | |
try { | |
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); | |
// 名前空間をサポートするか | |
factory.setNamespaceAware(true); | |
// DTD検証を行うか | |
factory.setValidating(false); | |
// XMLのパース | |
Document document = factory.newDocumentBuilder().parse("(XMLのURI)"); | |
// バージョン情報の取得 | |
String version = document.getDocumentElement().getAttribute("version"); | |
if (version.equals("1.0")) { | |
Schema schema = SchemaFactory.newInstance( | |
XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( | |
new URL("XMLスキーマバージョン1のURL")); | |
schema.newValidator().validate(new DOMSource(document)); | |
// バージョン1の処理 | |
} else if (version.equals("2.0")) { | |
Schema schema = SchemaFactory.newInstance( | |
XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( | |
new URL("XMLスキーマバージョン2のURL")); | |
schema.newValidator().validate(new DOMSource(document)); | |
// バージョン2の処理 | |
} else { | |
// エラー | |
} | |
} catch (Exception e) { | |
// エラー | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment