【问题标题】:validation XML against XSD java针对 XSD java 验证 XML
【发布时间】:2015-11-29 20:44:08
【问题描述】:

当我在线验证我的 xml 时,一切都很好。但是在eclipse中它不起作用。它返回一个错误:

SAX 异常:schema_reference.4:无法读取架构文档 'file:/C:/Users/ASUS/Downloads/Task3_XML/Task3_XML/weapon.xml',因为 1) 找不到该文档; 2) 文件无法读取; 3) 文档的根元素不是。

这是我的代码

public static void main(String[] args) {
     boolean isValid = validateXMLSchema("weapon.xml","weaponXSD.xml");
     if(isValid){
        System.out.println(args[1] + " is valid against " + args[0]);
     }else {
        System.out.println(args[1] + " is not valid against " + args[0]);
     }
  }


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));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new File(xmlPath)));
  } catch (IOException e){    
     System.out.println("Exception: "+e.getMessage());
     return false;
  }catch(SAXException e1){
     System.out.println("SAX Exception: "+e1.getMessage());
     return false;
  }
  return true;
}

我的 XML:

<?xml version="1.0" encoding="UTF-8"?>
<Gun>
  <Weapon>
    <Model>Пістолет «Форт-12»</Model>
    <Handy>one-handed</Handy>
    <Origin>Україна</Origin>
    <TTH>
      <carry>близька [0;500 m]</carry>
      <effectiveRange>10 m</effectiveRange>
      <availabilityClips>true</availabilityClips>
      <availabilityOptics>false</availabilityOptics>
    </TTH>
    <Material>метал</Material>
  </Weapon>
</Gun>

还有我的 XSD 简写:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"      xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Gun">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Weapon" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Model">`

如果您有任何想法,请写信给我,因为我不明白问题出在哪里。

【问题讨论】:

    标签: java xml xsd


    【解决方案1】:

    错误提示

    file:/C:/Users/ASUS/Downloads/Task3_XML/Task3_XML/weapon.xml
    

    不是 XSD 文件。

    您将xml 文件作为第一个参数传递给方法validateXMLSchema,而它期望xsd 文件作为第一个参数。

    你需要像这样调用那个方法:

    boolean isValid = validateXMLSchema("weaponXSD.xml", "weapon.xml");
    

    另外请将架构文件的扩展名更改为.xsd

    weaponXSD.xsd
    

    或者干脆

    weapon.xsd
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 2013-09-05
      • 2012-07-26
      • 1970-01-01
      • 2012-09-20
      • 2011-10-12
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多