【问题标题】:xml : how to reference a .xsd file at .xml file?xml:如何在 .xml 文件中引用 .xsd 文件?
【发布时间】:2014-04-29 14:18:44
【问题描述】:

我想在浏览器中查看我在 .xsd 文件中定义的 xml 文件。请为我检查以下两个文件并指出我需要做什么。这两个文件在同一个文件夹下。

员工.xml

 <?xml version="1.0"?>

<employee xmlns="http://www.w3schools.com" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="employee.xsd">

  <firstname>John</firstname>
  <lastname>Smith</lastname>
</employee>

employee.xsd

<xs:element name="employee">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string" fixed="red" />
      <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

【问题讨论】:

    标签: xml xsd


    【解决方案1】:

    您犯了两个错误:一个在架构文件中,另一个在 XML 文件的 xsi:schemaLocation 属性值的语法中。

    主要错误是您的employee.xsd 文件只是XML Schema 的一个片段。您应该完成employee.xsd 的包含。例如,

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema targetNamespace="http://www.w3schools.com/RedsDevils"
        elementFormDefault="qualified"
        xmlns="http://www.w3schools.com/RedsDevils employee.xsd"
        xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
        <xs:element name="employee">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="firstname" type="xs:string" fixed="red" />
                    <xs:element name="lastname" type="xs:string"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>
    

    和employee.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <employee xmlns="http://www.w3schools.com/RedsDevils"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.w3schools.com/RedsDevils employee.xsd">
    
        <firstname>John</firstname>
        <lastname>Smith</lastname>
    </employee>
    

    因为您在 XML 文件中定义了默认命名空间,所以架构位置属性 xsi:schemaLocation 必须由命名空间和架构路径组成,并以空格分隔。我更改了命名空间名称,使其更加独特:"http://www.w3schools.com/RedsDevils" 而不是 "http://www.w3schools.com"

    最后我可以补充一点,XML 文件employee.xml 不对应于架构employee.xsd,因为元素&lt;firstname&gt;John&lt;/firstname&gt; 的值为red,但可能正是您想要测试的。

    【讨论】:

    • @Oleg 是否可以指定“此 xml 中的每个 都应遵循相同的模式?”而不是在每个 标签中都需要 xsi:schemaLocation?
    • @DavidDoria:通过指定&lt;employee&gt; 的XML Schema,我们为它的所有孩子设置了模式(例如&lt;firstname&gt;&lt;lastname&gt;)。通常一组 xmlnsschemaLocation 仅用于 XML 文件的 root 元素。我的回答中的例子很短。例如,通常会将&lt;employees&gt; 作为具有许多&lt;employee&gt; 子元素的根元素。顺便说一下,为每个&lt;employee&gt; 定义一个模式,并另外指定&lt;employee&gt; 可以放置在根&lt;employees&gt; 元素内的位置。
    猜你喜欢
    • 2014-06-17
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多