xml使用schema文件创建实例(转)

我们定义了名为example.xsd一个xsd文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>

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

 targetNamespace="http://www.baidu.com"

 xmlns:tns="http://www.baidu.com" 

 elementFormDefault="qualified">

<element name="user">

<complexType>

<sequence>

<element name="username" type="string"/>

<element name="password" type="string"/>

</sequence>

</complexType>

</element>

</schema>

 

此时,我们要在xml当中使用其中的元素并进行对其中的元素进行赋值,得到的xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<user xmlns="http://www.baidu.com"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://www.baidu.com example.xsd">

  <username>小明</username>

  <password>xiaoming</password> 

</user>

1. xmlns="http://www.baidu.com"

在这个文件当中我们要使用user,我们要引用http://www.baidu.com这个包(命名空间),所以我们要使用xmlns="http://www.baidu.com"

 

2.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

导入xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"(这个是必须的),我的理解是,xsd就好像是一个类文件,然后xml就是一个实例,我们要创建实例就需要导入这个命名空间。

 

3.xsi:schemaLocation="http://www.baidu.com example.xsd"

schemaLocation属性有两个值。第一个值是需要使用的命名空间(e.g : http://www.baidu.com)。第二个值是供命名空间使用的 XML schema 的位置(e.g: example.xsd(xsd文件的文件名))

猜你喜欢

转载自carrotgrandpa.iteye.com/blog/2281929