大家好,这是我的 xml 文件,其中 xsd 定义为它的内部
<?xml version="1.0"?>
<catalog xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:x="urn:book">
<!-- START OF SCHEMA -->
<xsd:schema targetNamespace="urn:book">
<xsd:element name="book">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="genre" type="xsd:string"/>
<xsd:element name="price" type="xsd:float"/>
<xsd:element name="publish_date" type="xsd:date"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="number" type="xsd:integer"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<!-- END OF SCHEMA -->
<x:book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with
XML.</description>
<number>123.4 </number>
</x:book>
</catalog>
我想在java中验证它,我已经为java编写了下面的代码,它对于这个xml非常有效。
import java.io.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.*;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
public class TestValidation {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate("/*/*", new InputSource("E:\\abc.xml"), XPathConstants.NODESET);
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Validator validator = factory.newSchema(new DOMSource(nodes.item(0))).newValidator();
try {
validator.validate(new DOMSource(nodes.item(1)));
System.out.println("XML is valid.");
}
catch (SAXException ex) {
System.out.println("XML is not valid because " + ex.getMessage());
}
}
}
现在我想将 xsd 定义为一个单独的外部文件,我知道如何定义它,任何人都可以帮助我找到如何从这个 xml 调用该 xsd,然后我需要在我的 java 程序中进行任何更改