学了这次的视频,我了解了下一直不太懂的命名空间
命名空间的出现是为了解决dtd不能解决的xml的命名冲突问题,这次课的视频里,xsd文件没有定义自己的命名空间。
然后在book.xml中引入book.xsd的时候属性使用的是
xsi:noNamespaceSchemaLocation="book.xsd"
不指定命名空间,只指定用于模式校验的xsd文档的位置,这种写法,XML模式处理器已经可以校验到xml里的写法问题了。如图:具体报错:
The content of element 'book' is not complete. One of '{price}' is expected.
说明已经检验成功了
在这里老师用的是
xsi:noNamespaceSchemaLocation="{book.xsd}"
而这种写法在我的idea里面是报红的。
至于视频里老师不报红,我猜测不同工具的不同文件,可能工具没有识别出来语法错误,把验证插件给关闭了。为什么老师要多此一举,使用java的相关类,SchemaFactory进行解析,
是不是因为要让我们了解如果脱离eclipse或者相关IDE,没有XML解析器,在只有xml文件及xsd文件的基础上,java也可以完成使用schema对xml文档的校验。
(扩充:自己测试了一下似乎谷歌浏览器无法完成使用schema对xml文档的校验,不报任何错误。)
这点在视频里没有提到。。这里存在疑问:(******)
另外给大家一种使用命名空间的方式校验:targetNamespace在book.xsd中给当前命名空间起名字,名称任意:http://www.example.org/books 这个是可以更改的
<?xml version="1.0" encoding="UTF-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/books" elementFormDefault="qualified"> <xs:element name="books"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string"></xs:element> <xs:element name="author" type="xs:string"></xs:element> <xs:element name="price" type="xs:double"></xs:element> </xs:sequence> <xs:attribute name="id" type="xs:positiveInteger"></xs:attribute> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
book.xml 使用命名空间http://www.example.org/books
<?xml version="1.0" encoding="UTF-8" ?> <books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.example.org/books" xsi:schemaLocation="http://www.example.org/books book.xsd"> <book id="1001"> <name>html的使用</name> <author>张三</author> <price>51.6</price> </book> <book id="1002"> <name>css的使用</name> <author>李四</author> <price>40.6</price> </book> </books>
注释掉第一个book元素的price元素
结果:具体报错:The content of element 'book' is not complete. One of '{"http://www.example.org/books":price}' is expected.
想让老师解答一下带****号的那里的疑问!谢谢!