Java中针对xsd的XML验证

时间:2012-07-27 11:49:05

标签: java xml xsd

问题: 我们有几个服务通过XSLT生成相当数量的XML。我们没有任何XSD。我花时间创建了XSD,并想确认它们是正确的。目前,我正在尝试验证XSD和XML是否正确验证。

问题: 我有一个xsd(common.xsd)导入到所有的xsd中。它还没有公开托管,所以直到最近我才发现将common.xsd的完整路径放在AccountList.xsd中我才得以进一步发展。我现在收到以下内容:

  

org.xml.sax.SAXParseException; lineNumber:9; columnNumber:70; s4s-att-invalid-value:元素'element'中'type'的属性值无效。记录原因:UndeclaredPrefix:无法将'common:response'解析为QName:未声明前缀'common'。

我不知所措。我找不到在论坛中提出的示例或获得成功的源代码片段。我很感激帮助您成功验证我的xml。

common.xsd

<xs:schema  version="1.0" elementFormDefault="qualified" attributeFormDefault="unqualified"
        xmlns="http://www.myorg.com/xsd/gen_fin"
        xmlns:xs="http://www.w3.org/2001/XMLSchema" 
        targetNamespace="http://www.myorg.com/xsd/gen_fin">
    <xs:complexType name="response">
        <xs:sequence>
            <xs:element name="code" type="xs:string"/>
            <xs:element name="description" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

AccountList.xsd

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>

<xs:schema  version="1.0" elementFormDefault="qualified" attributeFormDefault="unqualified"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:tns="http://www.myorg.com/xsd/accList"
            targetNamespace="http://www.myorg.com/xsd/accList"
            xmlns:common="http://www.myorg.com/xsd/gen_fin">
    <xs:import namespace="http://www.myorg.com/xsd/gen_fin" 
               schemaLocation="/home/me/dev/projects/svn/myorg/xsd/src/main/resources/bg/gen_resp/common.xsd"/>

    <xs:element name="fundamo">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="response" type="common:response" minOccurs="1" maxOccurs="1"/>
                <xs:element name="transaction" type="tns:transaction" minOccurs="0" maxOccurs="1"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="transaction">
        <xs:sequence>
            <xs:element name="transactionRef" type="xs:string"/>
            <xs:element name="dateTime" type="xs:string"/>
            <xs:element name="userName" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Test.java

final InputStream commonXsdStream = getXsd(BG_GEN_RESP_XSD_PATH, COMMON);

ClassPathResource fullXsdListing = new ClassPathResource(BG_GEN_RESP_XSD_PATH);

File[] allXsds = fullXsdListing.getFile().listFiles();

for (File currentXsd : allXsds) {
    final int filenameLength = currentXsd.getName().length();
    final String filenameSanExt = currentXsd.getName().substring(0, filenameLength - 4);

    if (!IGNORE.contains(filenameSanExt)) {
        final InputStream xsltStream = getXslt(BG_GEN_RESP_XSLT_PATH, filenameSanExt);
        final InputStream xsdStream = getXsd(BG_GEN_RESP_XSD_PATH, filenameSanExt);

        TransformerFactory xmlTransformer = TransformerFactory.newInstance();
        Templates xsltTemplate = xmlTransformer.newTemplates(new StreamSource(xsltStream));
        final XSLToXMLConvertor converter = new XSLToXMLConvertor();
        String generatedXml = converter.getXML(inputData, xsltTemplate);

        LOG.info(generatedXml);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(lnew StreamSource(xsdStream));

        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(generatedXml)));

        /*
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        docBuilderFactory.setValidating(true);

        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        docBuilder.parse(new InputSource(new ByteArrayInputStream(generatedXml.getBytes("utf-8"))));
        */
        }
    }
}

1 个答案:

答案 0 :(得分:0)

定义名称空间和targetNamespace通常是个好主意,尽管正如Petru Gardea指出的那样,并非绝对必要。这是绝对有效的组合:

AccountList.xsd

<xs:schema
    version="1.0"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://www.myorg.com/xsd/accList"
    targetNamespace="http://www.myorg.com/xsd/accList"
    xmlns:common="http://www.myorg.com/xsd/gen_fin">

    <xs:import namespace="http://www.myorg.com/xsd/gen_fin" schemaLocation="common.xsd" />

    <xs:element name="fundamo">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="response" type="common:response"
                    minOccurs="1" maxOccurs="1" />
                <xs:element name="transaction" type="tns:transaction"
                    minOccurs="0" maxOccurs="1" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="transaction">
        <xs:sequence>
            <xs:element name="transactionRef" type="xs:string" />
            <xs:element name="dateTime" type="xs:string" />
            <xs:element name="userName" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>

common.xsd

<xs:schema
    version="1.0"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns="http://www.myorg.com/xsd/gen_fin"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.myorg.com/xsd/gen_fin">

    <xs:complexType name="response">
        <xs:sequence>
            <xs:element name="code" type="xs:string" />
            <xs:element name="description" type="xs:string" />
        </xs:sequence>
    </xs:complexType>
</xs:schema>

NewFile.xml(基于该架构):

<tns:fundamo xmlns:p="http://www.myorg.com/xsd/gen_fin"
    xmlns:tns="http://www.myorg.com/xsd/accList" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.myorg.com/xsd/accList AccountList.xsd ">
    <tns:response>
        <p:code>p:code</p:code>
        <p:description>p:description</p:description>
    </tns:response>
</tns:fundamo>

ValidateXml.java:

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class ValidateXml {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
            Document document = parser.parse(new File("NewFile.xml"));

            Schema schema = schemaFactory.newSchema(new File("AccountList.xsd"));
            Validator validator = schema.newValidator();

            validator.validate(new DOMSource(document));
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

与“无法找到元素声明”相关的错误通常与不支持命名空间的XML文档有关。验证您的两个XSD的路径是否正确,并返回到构建可识别名称空间的XML文档的代码块。