尝试针对 xsd 文件验证 xml 时未找到文件异常

  • 本文关键字:文件 异常 xml 验证 xsd java xml xsd
  • 更新时间 :
  • 英文 :


当我尝试运行以下代码时,我不断收到"找不到文件"异常:

public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try{
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
javax.xml.validation.Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
return true;
}
catch (Exception e){
System.out.println(e);
return false;
}
}

这就是我调用方法的方式:

Boolean value = validateXMLSchema("shiporder.xsd",xmlfile);

ShipOrder 是编译器在项目文件夹中查找的文件的名称。

xmlfile 变量是一个字符串,其中包含将与 xds 文件进行比较的 xml 文件。

即使我已经检查了文件的位置是否正确,我也收到找不到文件异常。

这是我的 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>

这是 xsd 文件:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>

有谁知道为什么我会遇到这个问题?

你没有告诉 File(( 构造函数文件在哪里。 此构造函数将文件名解析为抽象路径名,并根据依赖于系统的默认目录解析结果。 这可能不是你想要的。

如果 xsd 位于项目中的某个位置,请使用yourProject.YourReader.class.getResource(xsdPath)。 xsdPath 将是一个"相对"资源名称,它是相对于类的包处理的。或者,您可以使用前导斜杠指定"绝对"资源名称。 例如,如果 xsd 与其读取器位于同一目录中,请使用getResource("shiporder.xsd")。 如果要从项目根目录开始,请使用getResource("/path/to/shiporder.xsd")

然后,如果需要,可以使用new File(resource.toURI())将此资源转换为文件

对于您的代码:

public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try{
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(ThisClass.class.getResource("/path/to/shiporder.xsd").toURI());
...
}}

最新更新