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而已