【问题标题】:xml validation against xsd by using spring java使用spring java对xsd进行xml验证
【发布时间】:2013-10-25 19:20:43
【问题描述】:

/我遇到了问题,因为我有三个引用的 xsd 和我来验证作为 jdom 元素的 xml。我得到的例外是“找不到清除”。代码如下: 输入参数为:元素参数/

     DOMOutputter outputter = new DOMOutputter();
    org.jdom2.Document document=new org.jdom2.Document();
    document.addContent(param.clone());
org.w3c.dom.Document doc=outputter.output(document);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Source xmlSource = new DOMSource(doc);
    Result outputTarget = new StreamResult(outputStream);
    TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
    InputStream xml = new ByteArrayInputStream(outputStream.toByteArray()); 

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
    DocumentBuilder builder;   
    factory.setNamespaceAware(true);
    builder = factory.newDocumentBuilder();

    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    // create a grammar object.
    Source[] source = {
            new StreamSource(new File("H:/ref2.xsd")),
            new StreamSource(new File("H:/ref1.xsd")),
            new StreamSource(new File("H:/ref.xsd"))};
    Schema schemaGrammar = schemaFactory.newSchema(source);
    validator.validate(new StreamSource(xml));

//请推荐

【问题讨论】:

标签: java xml spring xsd


【解决方案1】:
URL xsdUrlA = this.getClass().getResource("a.xsd");
URL xsdUrlB = this.getClass().getResource("b.xsd");
URL xsdUrlC = this.getClass().getResource("c.xsd");

SchemaFactory schemaFactory = schemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//---
String W3C_XSD_TOP_ELEMENT =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
   + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\">\n"
   + "<xs:include schemaLocation=\"" +xsdUrlA.getPath() +"\"/>\n"
   + "<xs:include schemaLocation=\"" +xsdUrlB.getPath() +"\"/>\n"
   + "<xs:include schemaLocation=\"" +xsdUrlC.getPath() +"\"/>\n"
   +"</xs:schema>";
Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(W3C_XSD_TOP_ELEMENT), "xsdTop"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 2013-10-30
    • 2014-01-16
    • 2014-03-27
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多