如何用java验证XML schema

以前验证XML一直使用dtd的,今天尝试着用xsd作验证,可是网上的例子一直跑不起来。折腾了半天才发现是例子里面对于XML文件的命名空间没有设置清楚,这里解决下方案记录:

 

[note.xml]

 

<?xml version="1.0"?>
<note xmlns="http://adcoup.baidu.com/schema/note">
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend!</body>
</note>

 

  网上的例子就是在这里没设置对xmlns,这里的xmlns一定要和下面note.xsd中的targetNamespace和xmlns一致

 

[note.xsd]

 

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
	targetNamespace="http://adcoup.baidu.com/schema/note" xmlns="http://adcoup.baidu.com/schema/note"
	elementFormDefault="qualified">
	<xs:element name="note">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="to" type="xs:string" />
				<xs:element name="from" type="xs:string" />
				<xs:element name="heading" type="xs:string" />
				<xs:element name="body" type="xs:string" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>

 

[java]

 

  

  String configFileLocation = "/note.xml";
        String xsdFileLocation = "/note.xsd";
        InputStream configInputStream = this.getClass().getResourceAsStream(configFileLocation);
        if (configInputStream == null) {
            throw new IllegalArgumentException("can not find resource[" + configFileLocation + "]");
        }

        InputStream xsdInputStream = this.getClass().getResourceAsStream(xsdFileLocation);
        if (xsdInputStream == null) {
            throw new IllegalArgumentException("can not find resource[" + xsdFileLocation + "]");
        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new SAXSource(new InputSource(xsdInputStream)));
        factory.setSchema(schema);

        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new RuntimeException(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new RuntimeException(exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new RuntimeException(exception);
            }
        });

        document = builder.parse(configInputStream);

        System.out.println(document);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值