XML検証-複数のxsdの使用

freepublicview:

xmlを検証する2つのxsdファイルがあります。しかし、問題は私のコードが1つのxsdだけを取ることです。次のコードで他のxsdを使用するにはどうすればよいですか?2番目のxsdファイルをどこに配置/呼び出しすればよいかわからない。

             private void validate(File xmlF,File xsd1,File xsd2) {
                    try {
                        url = new URL(xsd.toURI().toString());//  xsd1
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }


                    source = new StreamSource(xml); // xml
                    try {
                        System.out.println(url);
                        schema = schemaFactory.newSchema(url);
                    } catch (SAXException e) {
                        e.printStackTrace();
                    }
                    validator = schema.newValidator();
                    System.out.println(xml);
                    try {
                        validator.validate(source);
                    } catch (SAXException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
Wivani:

SOやGoogleで検索すると、多くのヒットがあります。それらの1つはこの質問です。ここで、作成者は自分の解決策を見つけ、次のコードを報告して、複数のxsdをバリデーターに追加します。

Schema schema = factory().newSchema(new Source[] {
  new StreamSource(stream("foo.xsd")),
  new StreamSource(stream("Alpha.xsd")),
  new StreamSource(stream("Mercury.xsd")),
});

ただし、InputStreamonを直接使用するStreamSource場合、リゾルバーは参照されているXSDファイルをロードできません。たとえば、ファイルxsd1が3番目のファイル(ではないxsd2をインポートまたは含む場合、スキーマの作成は失敗します。システム識別子(setSystemId)を設定するか、または(さらに良い)StreamSource(File f)コンストラクターを使用する必要があります。

あなたのサンプルコードに調整:

try {
  schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  schema = schemaFactory.newSchema(new Source[] {
    new StreamSource(xsd1), new StreamSource(xsd2)
  });
} catch (SAXException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

注意:

クラスパスリソースを使用する場合、StreamSource(String systemId)(を作成するのではなくFileコンストラクターを使用します。

new StreamSource(getClass().getClassLoader().getResource("a.xsd").toExternalForm());

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事