Java 怎么验证XML

2019年7月29日21:01:55Java 怎么验证XML已关闭评论 330 1015字阅读3分23秒

1.简介

Java 怎么验证XML?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class Main {

  public void run(String xmlFile, String validationFile) {
    boolean valid = true;
    SchemaFactory sFactory = SchemaFactory
        .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
      Schema schema = sFactory.newSchema(new File(validationFile));
      Validator validator = schema.newValidator();
      Source source = new StreamSource(new File(xmlFile));
      validator.validate(source);
    } catch (SAXException | IOException | IllegalArgumentException ex) {
      valid = false;
    }
    System.out.printf("XML file is %s.\n", valid ? "valid" : "invalid");
  }

  public static void main(String[] args) {
    if (args.length != 2) {
      System.out
          .println("Usage: java Main <xmlFile> <validationFile>");
      System.exit(1);
    }
    Main app = new Main();
    app.run(args[0], args[1]);
  }
}

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