使用针对xsd的验证程序验证soap xml

时间:2016-02-09 12:24:14

标签: java xml validation xsd

我想针对给定的xsd验证soap请求xml,请求可能很大,所以我不能只提取soap body的内容并进行验证,而是基于流的验证。我已经为soap body(请求部分)创建了xsd,它不包含任何有关soap标头的信息,因此验证失败了,我所做的是将soap模式导入到我的xsd,以便验证器可以识别soap标头。它有效,但即使肥皂体不含任何东西,验证也会成功。我们如何在xsd中指定soap body至少应包含特定元素?我修改的xsd粘贴在下面。感谢。

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema attributeFormDefault="qualified" targetNamespace="urn:sample"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="sample">
    <xsd:import namespace="http://schemas.xmlsoap.org/soap/envelope/"
                schemaLocation="http://schemas.xmlsoap.org/soap/envelope/"/>
    <xsd:complexType name="type1">
        <xsd:sequence>
            <xsd:element name="item" type="tns:type2" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="type3">
        <xsd:sequence>
            <xsd:element name="item" type="tns:type4" minOccurs="0" maxOccurs="unbounded"/>
        </xsd:sequence>
    </xsd:complexType>
    <xsd:element name="element1">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="RETURN" type="tns:type3" minOccurs="0"/>
                <xsd:element name="HEADER" type="tns:type1"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
    <xsd:element name="element2">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="RETURN" type="tns:type3" minOccurs="0"/>
                <xsd:element name="ERRORS" type="xsd:int"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

1 个答案:

答案 0 :(得分:1)

尝试类似的内容:

SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
FileInputStream fileInputStream = new FileInputStream(new File("Simple.xsd"));  
Schema schema = factory.newSchema(new StreamSource(fileInputStream));  
Validator val = schema.newValidator(); 
FileInputStream fileInputStream2 = new FileInputStream(new File("Input.xml"));  
val.validate(new StreamSource(fileInputStream2));