首頁  >  文章  >  使用作為檔案載入的 XSD 進行 XML 驗證與輸入流

使用作為檔案載入的 XSD 進行 XML 驗證與輸入流

WBOY
WBOY轉載
2024-02-09 15:09:091000瀏覽

在php小編草莓的指導下,我們將探討使用作為檔案載入的XSD進行XML驗證與輸入流程的方法。當我們處理XML資料時,驗證是非常重要的一步,以確保資料的正確性和完整性。透過使用XSD(XML Schema Definition)文件,我們可以定義XML文件的結構和約束。透過載入XSD檔案並將其用於驗證輸入的XML流,我們可以輕鬆地偵測和處理不符合規定的數據,從而提高應用程式的可靠性和安全性。接下來,我們將詳細介紹如何使用XSD檔案進行XML驗證和輸入流處理。

問題內容

如果 xsd 作為檔案或資源加載,我在 xml 驗證中會遇到不同的行為。

如果我將 xsd 作為文件加載,一切都很好並且驗證工作正常:

schemafactory sf = schemafactory.newinstance(xmlconstants.w3c_xml_schema_ns_uri);
schema schema = sf.newschema(new classpathresource("my/perfect/path/myfile.xsd").getfile());
validator validator = schema.newvalidator();
validator.validate(sourcetovalidate);

相反,因為我決定將xsd 檔案包含到jar 中,所以我將其作為資源加載,但行為不同,當我構造架構時,我陷入saxparseexception ,並且錯誤抱怨中的某有些問題將xsd 檔案中的名稱解析為型別定義。 xsd 檔案絕對正確

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("my/perfect/path/myFile.xsd");
Source schemaSource = new StreamSource(inputStream);
Schema schema = sf.newSchema(schemaSource); // here i get the SAXParseException
Validator validator = schema.newValidator();
validator.validate(sourceToValidate);

我真的不明白為什麼載入 xsd 作為 resourceasstream 會導致不同的行為

我使用 jaxb 進行 xml 驗證

解決方法

我猜您的 xsd 引用了其他 xsd,並且您的驗證器不知道如何解析這些引用。

您可能需要提供 lsresourceresolvervalidator

#
classloader loader = getclass().getclassloader();
lsresourceresolver resolver = new lsresourceresolver() {
   public lsinput resolveresource(string type, string namespaceuri, string publicid, string systemid, string baseuri) {
      inputstream stream = loader.getresourceasstream(systemid);
      if (stream == null) throw new runtimeexception("could not find " + systemid);
      lsinput input = new dominputimpl();
      input.setpublicid(publicid);
      input.setsystemid(systemid);
      input.setbaseuri(baseuri);
      input.setbytestream(stream);             
      return input;
   }
};
validator validator = schema.newvalidator();
validator.setresourceresolver(resolver);

您還需要透過呼叫 streamsource 的兩個參數建構子來在 inputsource 上設定 systemid

String xsdPath = "my/perfect/path/myFile.xsd";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xsdPath);
Source schemaSource = new StreamSource(inputStream, xsdPath);

請參考streamsource(inputstream, string)

#

以上是使用作為檔案載入的 XSD 進行 XML 驗證與輸入流的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除