很多應用程式與網站都靠 XML 檔做設定,而最終產品是交到客戶手上的。這意味著設定檔往往也得由客戶自己撰寫——一旦如此,我們就無法保證 XML 一定寫得正確。
為了解決這個問題,這裡提供一個驗證類別,主要功能是檢查 XML 檔案是否符合預先定義好的 XSD 結構規範。以下先給 Java 版本,接著附上 C# 版本。
package common.XML.validator;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
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;
/**
* @author suyuan
*/
public class XMLSchemaValidator {
private boolean isValid = true;
private String XMLErr = "";
public boolean isValid() {
return isValid;
}
public String getXMLErr() {
return XMLErr;
}
public XMLSchemaValidator() {
}
/** 傳入 XML 字串與 XSD(以 URL 表示) */
public boolean ValidXmlDoc(String XML, URL schema) {
StringReader reader = new StringReader(XML);
return ValidXmlDoc(reader, schema);
}
/** 傳入 XML 讀取器與 XSD(以 URL 表示) */
public boolean ValidXmlDoc(Reader XML, URL schema) {
try {
InputStream schemaStream = schema.openStream();
Source xmlSource = new StreamSource(XML);
Source schemaSource = new StreamSource(schemaStream);
return ValidXmlDoc(xmlSource, schemaSource);
} catch (IOException e) {
isValid = false;
XMLErr = e.getMessage();
return false;
}
}
/** 傳入 XML 字串與 XSD(以 File 表示) */
public boolean ValidXmlDoc(String XML, File schema) {
StringReader reader = new StringReader(XML);
return ValidXmlDoc(reader, schema);
}
/** 傳入 XML 讀取器與 XSD(以 File 表示) */
public boolean ValidXmlDoc(Reader XML, File schema) {
try {
FileInputStream schemaStream = new FileInputStream(schema);
Source xmlSource = new StreamSource(XML);
Source schemaSource = new StreamSource(schemaStream);
return ValidXmlDoc(xmlSource, schemaSource);
} catch (IOException e) {
isValid = false;
XMLErr = e.getMessage();
return false;
}
}
/** 核心方法:以 Source 物件進行驗證 */
public boolean ValidXmlDoc(Source XML, Source schemaSource) {
try {
SchemaFactory schemafactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
if (XML == null) {
return false;
}
Schema schema = schemafactory.newSchema(schemaSource);
Validator valid = schema.newValidator();
valid.validate(XML);
return true;
} catch (SAXException e) {
isValid = false;
XMLErr = e.getMessage();
return false;
} catch (IOException e) {
isValid = false;
XMLErr = e.getMessage();
return false;
} catch (Exception e) {
isValid = false;
XMLErr = e.getMessage();
return false;
}
}
}
這個類別圍繞著 JAXP 的 javax.xml.validation 套件:先用 SchemaFactory 依 XSD 建出 Schema 物件,再取出 Validator 進行驗證。任何不符合結構的情況都會拋出 SAXException,我們把訊息存進 XMLErr 供呼叫端取用。多個多載版本存在的目的,是讓呼叫端可以依手上持有的資料形式(字串、Reader、File、URL、Source)直接傳入,不必自己轉換。
package common.XML.validator;
import java.io.*;
import java.net.URL;
public class testXMLValidator {
public static void main(String[] args) {
InputStream xmlStream = testXMLValidator.class.getResourceAsStream("test.xml");
Reader xmlReader = new InputStreamReader(xmlStream);
URL schema = testXMLValidator.class.getResource("valid.xsd");
XMLSchemaValidator xmlvalid = new XMLSchemaValidator();
System.out.println(xmlvalid.ValidXmlDoc(xmlReader, schema));
System.out.print(xmlvalid.getXMLErr());
}
}
<xs:schema id="XSDSchemaTest"
xmlns:xs="https://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:simpleType name="FamilyMemberType">
<xs:restriction base="xs:string">
<xs:enumeration value="384" />
<xs:enumeration value="385" />
<xs:enumeration value="386" />
<xs:enumeration value="" />
</xs:restriction>
</xs:simpleType>
<xs:element name="Answer">
<xs:complexType>
<xs:sequence>
<xs:element name="ShortDesc" type="FamilyMemberType" />
<xs:element name="AnswerValue" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
這份結構定義約束了兩件事:ShortDesc 只能取 384、385、386 或空字串這幾個列舉值;AnswerValue 必須是整數。
<?xml version="1.0" encoding="utf-8" ?>
<Answer>
<ShortDesc>385</ShortDesc>
<AnswerValue>1</AnswerValue>
</Answer>
以下是 C# 版本的對應實作(原始版本出自國外作者,前述 Java 類別即由其翻譯而來)。它同樣提供字串、XmlDocument 與 StringReader 三種入口,並透過 ValidationEventHandler 回呼收集錯誤訊息。
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
namespace ProtocolManager.WebApp
{
/// <summary>
/// This class validates an xml string or xml document against an XML schema.
/// It has public methods that return a boolean value depending on the validation
/// of the XML.
/// </summary>
public class XMLSchemaValidator
{
private bool isValidXML = true;
private string validationError = "";
/// <summary>
/// Empty Constructor.
/// </summary>
public XMLSchemaValidator()
{
}
/// <summary>
/// Public get/set access to the validation error.
/// </summary>
public String ValidationError
{
get
{
return "<ValidationError>" + this.validationError + "</ValidationError>";
}
set
{
this.validationError = value;
}
}
/// <summary>
/// Public get access to the isValidXML attribute.
/// </summary>
public bool IsValidXML
{
get
{
return this.isValidXML;
}
}
/// <summary>
/// This method is invoked when the XML does not match the XML Schema.
/// </summary>
private void ValidationCallBack(object sender, ValidationEventArgs args)
{
// The XML does not match the schema.
isValidXML = false;
this.ValidationError = args.Message;
}
/// <summary>
/// Validates an xml string against an XML schema.
/// </summary>
public bool ValidXmlDoc(string XML, string schemaNamespace, string schemaUri)
{
try
{
// Is the XML string valid?
if (XML == null || XML.Length < 1)
{
return false;
}
StringReader srXml = new StringReader(XML);
return ValidXmlDoc(srXml, schemaNamespace, schemaUri);
}
catch (Exception ex)
{
this.ValidationError = ex.Message;
return false;
}
}
/// <summary>
/// Validates an xml document against an XML schema.
/// </summary>
public bool ValidXmlDoc(XmlDocument XML, string schemaNamespace, string schemaUri)
{
try
{
// Is the XML object valid?
if (XML == null)
{
return false;
}
// Write the document out to a string.
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
XML.WriteTo(xw);
string strXml = sw.ToString();
StringReader srXml = new StringReader(strXml);
return ValidXmlDoc(srXml, schemaNamespace, schemaUri);
}
catch (Exception ex)
{
this.ValidationError = ex.Message;
return false;
}
}
/// <summary>
/// Validates an xml string (via StringReader) against an XML schema.
/// </summary>
public bool ValidXmlDoc(StringReader XML, string schemaNamespace, string schemaUri)
{
// Continue?
if (XML == null || schemaNamespace == null || schemaUri == null)
{
return false;
}
isValidXML = true;
XmlValidatingReader vr;
XmlTextReader tr;
XmlSchemaCollection scheMacol = new XmlSchemaCollection();
scheMacol.Add(schemaNamespace, schemaUri);
try
{
// Read the XML.
tr = new XmlTextReader(XML);
// Create the validator.
vr = new XmlValidatingReader(tr);
// Set the validation type.
vr.ValidationType = ValidationType.Auto;
// Add the schema.
if (scheMacol != null)
{
vr.Schemas.Add(scheMacol);
}
// Set the validation event handler.
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Read the XML.
while (vr.Read())
{
}
vr.Close();
return isValidXML;
}
catch (Exception ex)
{
this.ValidationError = ex.Message;
return false;
}
finally
{
// Clean up
vr = null;
tr = null;
}
}
}
}
兩個版本的差異主要在 API 風格:Java 走 JAXP 的 Schema/Validator 模式,例外透過 catch 捕捉;.NET 則用 XmlValidatingReader 搭配 ValidationEventHandler,驗證錯誤以事件回呼形式回報,因此能把錯誤訊息寫進屬性而不必中斷流程。核心思路是一致的——先載入結構定義,再讓解析器在讀過整份 XML 的過程中逐一比對。
把這個類別放進專案裡,以後需要驗證客戶提供的設定檔時就能直接取用,也能作為一個隨手可查的參考範本。