简体   繁体   English

无法使用XSD架构验证XML

[英]unable to validate the XML with XSD schema

I am new to XML validation. 我是XML验证的新手。

My XSD is 我的XSD是

<xsd:complexType name="RootForm">
    <xsd:sequence>
        <xsd:element name="TRADE" type="RecordForm" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:sequence>

    <xsd:attribute name="ASOF_DATE" use="required">
        <xsd:simpleType>
            <xsd:restriction base="xsd:string">
                <xsd:pattern value="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"/>
            </xsd:restriction>
        </xsd:simpleType>
    </xsd:attribute>
    <xsd:attribute name="CREATE_DATE" use="required">
        <xsd:simpleType>
            <xsd:restriction base="xsd:string">
                <xsd:pattern value="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"/>
            </xsd:restriction>
        </xsd:simpleType>
    </xsd:attribute>
    <xsd:attribute name="RECORDS" type="xsd:integer" use="required"/>
</xsd:complexType>

The code that i an running is: 我正在运行的代码是:

SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    InputSource i = new InputSource("X:/workspace/XMLValidation/src/xml/trades.xml");
    InputSource i1 = new InputSource("X:/workspace/XMLValidation/src/xml/transactions.xsd");
    SAXParser saxParser = spf.newSAXParser();
    saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",  "http://www.w3.org/2001/XMLSchema");
    saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", i1);
    XMLReader xmlReader = saxParser.getXMLReader();
   // xmlReader.setContentHandler(new SimpleErrorHandler());
    xmlReader.setErrorHandler(new SimpleErrorHandler());

    try {
        xmlReader.parse(i);
    } catch (IOException e) {
        e.printStackTrace();
    }

I get the below exception: 我得到以下异常:

src-resolve.4.2: Error resolving component 'RootForm'. It was detected that 'RootForm' is in namespace 'http://www.w3schools.com', but components from this namespace are not referenceable from schema document 'file:///X:/workspace/XMLValidation/src/xml/transactions.xsd'. If this is the incorrect namespace, perhaps the prefix of 'RootForm' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'file:///X:/workspace/XMLValidation/src/xml/transactions.xsd'.
   Public ID: null
   System ID: file:///X:/workspace/XMLValidation/src/xml/transactions.xsd
   Line number: 6
   Column number: 52
   Message: src-resolve.4.2: Error resolving component 'RootForm'. It was detected that 'RootForm' is in namespace 'http://www.w3schools.com', but components from this namespace are not referenceable from schema document 'file:///X:/workspace/XMLValidation/src/xml/transactions.xsd'. If this is the incorrect namespace, perhaps the prefix of 'RootForm' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'file:///X:/workspace/XMLValidation/src/xml/transactions.xsd'.
cvc-elt.1: Cannot find the declaration of element 'TRANSACTIONS'.

Can any one please help me what im doing wrong in the xsd file 任何人都可以帮我在xsd文件中做错什么吗

Thanks Avnish 感谢Avnish

Can you please share the XML file you are parsing as well? 您能否也共享您正在解析的XML文件? Also the "RecordForm" type that the Trade element takes is not defined in the schema. 此外,在架构中也未定义Trade元素采用的“ RecordForm”类型。 Try including that and see. 尝试包括它,看看。 The namespace that you are using should be imported to distinguish the elements in the XML. 应该导入您正在使用的名称空间以区分XML中的元素。

Here is the correct ans from my side for yours which will surely help you out: 这是我身边最适合您的答案,肯定会帮助您:

Firstly the xml which you had was not of proper syntax which i have corrected in here: 首先,您所拥有的xml语法不正确,我已经在此处进行了更正:

<TRANSACTIONS xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="./transactions.xsd" ASOF_DATE="6/10/2011"  CREATE_DATE="6/10/2011" RECORDS="1769"> 
<TRADE> 
<ACCRUAL_DT>
09/22/2012
</ACCRUAL_DT> 
<COUNTERPARTY_CODE>
US
</COUNTERPARTY_CODE> 
<CUSIP>
BRS87R7N9
</CUSIP> 
<DESC_INSTMT>
CFD COOKSON GROUP PLC
</DESC_INSTMT> 
<DESK/>
</TRADE> 
</TRANSACTIONS>

Now simple go to the site: http://www.freeformatter.com/xsd-generator.html 现在,简单地转到该站点: http : //www.freeformatter.com/xsd-generator.html

Enter the XML mentioned above and click Generate XSD Schema. 输入上面提到的XML,然后单击Generate XSD Schema。 So now the schema would be generated and thereafter save it in your local disk and then run the code below to check and verify it! 因此,现在将生成架构,然后将其保存在本地磁盘中,然后运行以下代码进行检查和验证!

package your_package name;
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class XMLValidator
{

public void validate() {
    File xmlFile = new File(Provide the xml file location (disk) in double quotes);
    File xsdFile = new File(Provide the xml file location (disk) in double quotes);
    boolean retStat = this.validateSchema(xmlFile, xsdFile);
    if(retStat){    
        System.out.println("Validated");
    }       
    else
        System.out.println("Not Valid");
}

private boolean validateSchema(File xml, File xsd){
    Schema schema = null;
    try{
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(xsd);
    }catch (SAXException e) {
        e.printStackTrace();
        return false;

    }catch(Exception fnEx){
        fnEx.printStackTrace();
        return false;
    }

    if(null != schema){
        Validator validator = schema.newValidator();

        try {
            validator.validate(new StreamSource(xml));
            return true;
        } catch (SAXException e) {
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return false;
}

public static void main(String args[]){
    XMLValidator newObj=new XMLValidator();
    newObj.validate();
}

} }

And therby by solved!! 和therby解决了!

The namespace that you are using should be imported to distinguish the elements in the XML. 应该导入您正在使用的名称空间以区分XML中的元素。

Here is the XSD to reuse the ComplexTypes: 这是重用ComplexType的XSD:

<?xml version="1.0" encoding="utf-16"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="TRANSACTIONS" type="RootForm" />
  <xsd:complexType name="RootForm">
    <xsd:sequence>
      <xsd:element name="TRADE" type="RecordForm" />
    </xsd:sequence>
    <xsd:attribute name="xsi:noNamespaceSchemaLocation" type="xsd:string" />
    <xsd:attribute name="ASOF_DATE" type="xsd:dateTime" />
    <xsd:attribute name="CREATE_DATE" type="xsd:dateTime" />
    <xsd:attribute name="RECORDS" type="xsd:int" />
  </xsd:complexType>
  <xsd:complexType name="RecordForm">
    <xsd:sequence>
      <xsd:element name="ACCRUAL_DT" type="xsd:dateTime" />
      <xsd:element name="COUNTERPARTY_CODE" type="xsd:string" />
      <xsd:element name="CUSIP" type="xsd:string" />
      <xsd:element name="DESC_INSTMT" type="xsd:string" />
      <xsd:element name="DESK" type="xsd:string" />
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM