0

我有一个 XML 文件和 XSD。在这种形式下它工作正常:

<tns:Users xmlns:tns="http://www.example.org/NewXMLSchema">
    <User>
        <FirstName>Max</FirstName>
        <LastName>Gordon</LastName>
        <Salary>80000</Salary>
    </User>
    <User>
        <FirstName>Alex</FirstName>
        <LastName>Disel</LastName>
        <Salary>75000</Salary>
    </User>
</tns:Users>

<schema xmlns="http://www.w3.org/2001/XMLSchema"  
        targetNamespace="http://www.example.org/NewXMLSchema" 
        xmlns:tns="http://www.example.org/NewXMLSchema">
  <element name="Users">
    <complexType>
      <sequence maxOccurs="unbounded" minOccurs="1">
        <element name="User">
          <complexType>
            <sequence>
              <element name="FirstName" type="string"/>
              <element name="LastName" type="string"/>
              <element name="Salary" type="int"/>
            </sequence>
          </complexType>
        </element>
      </sequence>
    </complexType>
  </element>
</schema>

我想知道为什么它不在另一个中:如果我在 xml 文件中省略了 tns 前缀?我的意思是它会成为一个默认的命名空间:

<Users xmlns="http://www.example.org/NewXMLSchema">
    <User>
        <FirstName>Max</FirstName>
        <LastName>Gordon</LastName>
        <Salary>80000</Salary>
    </User>
    <User>
        <FirstName>Alex</FirstName>
        <LastName>Disel</LastName>
        <Salary>75000</Salary>
    </User>
</Users>
4

1 回答 1

2

Because these are different XML documents.

In the first XML:

<tns:Users xmlns:tns="http://www.example.org/NewXMLSchema">
    <User>
        <FirstName>Max</FirstName>
        <LastName>Gordon</LastName>
        <Salary>80000</Salary>
    </User>
    <User>
        <FirstName>Alex</FirstName>
        <LastName>Disel</LastName>
        <Salary>75000</Salary>
    </User>
</tns:Users>

only the root element Users is in http://www.example.org/NewXMLSchema namespace. All other elements are in {no namespace}.

This corresponds to your XML schema. It does define the target namespace. But it applies only to global element Users. All other elements are declared locally, and their namespace is determined by the elementFormDefault attribute of the <schema ...> element. You don't specify this attribute, but it exists and its default value is "unqualified". That means that all local elements have no namespace.

Now, let's look in your second XML:

<Users xmlns="http://www.example.org/NewXMLSchema">
    <User>
        <FirstName>Max</FirstName>
        <LastName>Gordon</LastName>
        <Salary>80000</Salary>
    </User>
    <User>
        <FirstName>Alex</FirstName>
        <LastName>Disel</LastName>
        <Salary>75000</Salary>
   </User>
</Users>

Here, you bluntly specify that all elements are in http://www.example.org/NewXMLSchema namespace (both the root and everything else). But this doesn't comply with your XML schema!

于 2013-08-11T06:45:54.710 回答