JAXP 利用xml schema 验证xml的合法性

xml schema 注意:

注意 schema文件只写xmlns 就可以了 ,配置其他的有问题(本人对xml schema 命名空间啥的很不熟, 不太会配哦)

<schema xmlns="http://www.w3.org/2001/XMLSchema">

<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema"> <element name="post"> <complexType> <sequence> <element name="id" type="long"></element> <element name="tiebaName" type="string"></element> <element name="url" type="string"></element> <element name="title" type="string"></element> <element name="author" type="string"></element> <element name="ip" type="string"></element> </sequence> </complexType> </element> </schema>

xml 文件

<?xml version="1.0" encoding="UTF-8"?> <post xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <id>0</id> <tiebaName>tiebaName</tiebaName> <url>url</url> <title>title</title> <author>author</author> <ip>ip</ip> </post>

String path = PostMarshall.class.getClassLoader().getResource("com/jaxb/tieba/").getPath(); JAXBContext factory = JAXBContext.newInstance(Post.class); // 创建 schema Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File(path,"post.xsd")); // 创建 marshaller Marshaller ms = factory.createMarshaller(); Post post = new Post(); Unmarshaller ums = factory.createUnmarshaller(); ums.setSchema(schema); post = (Post) ums.unmarshal(new File(path,"newFile.xml")); System.out.println(post.getAuthor());

如果xml 不符合规范 将会报异常:

例如 如果ip属性不写将会报异常。反之则不会。 只是ip为null而已

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值