首页javadomJava HTML/XML - 如何使用XML模式验证XML

Java HTML/XML - 如何使用XML模式验证XML

我们想知道如何使用XML模式验证XML。
import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {

  public static void main(String[] args) throws Exception {
    SchemaFactory sf = SchemaFactory
        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("data.xsd"));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setSchema(schema);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File("data.xml"));

    Element result = document.getElementById("abc");
    System.out.println(result);
  }

}