2016-08-20 41 views
1

我正在閱讀Apress的書籍「Java XML和JSON」。我創建的文件recipe.xml但不是有效的:錯誤:外部資源http://www.example.com/未註冊

<?xml version="1.0"?> 
<recipe xmlns="http://www.tutortutor.ca/" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://www.tutortutor.ca/schemas recipe.xsd"> 
    <title>Grilled Cheese Sandwich</title> 
    <ingredients> 
     <ingredient qty="2">bread slice</ingredient> 
     <ingredient>cheese slice</ingredient> 
     <ingredient qty="2">margarine pat</ingredient> 
    </ingredients> 
    <instructions> 
     Place frying pan on element and select medium heat. For each bread 
     slice, smear one pat of margarine on one side of bread slice. Place 
     cheese slice between bread slices with margarine-smeared sides away 
     from the cheese. Place sandwich in frying pan with one 
     margarine-smeared side in contact with pan. Fry for a couple of 
     minutes and flip. Fry other side for a minute and serve. 
    </instructions> 
</recipe> 


recipe.xsd

<?xml version="1.0" encoding="UTF-8" ?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:element name="title" type="xs:string"/> 
    <xs:element name="instructions" type="xs:string"/> 
    <xs:attribute name="qty" type="xs:unsignedInt" default="1"/> 
    <xs:element name="recipe"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element ref="title"/> 
       <xs:element ref="ingredients"/> 
       <xs:element ref="instructions"/> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
    <xs:element name="ingredients"> 
     <xs:complexType> 
      <xs:sequence> 
       <xs:element ref="ingredients" maxOccurs="unbounded"/> 
      </xs:sequence> 
     </xs:complexType> 
    </xs:element> 
    <xs:element name="ingredient"> 
     <xs:complexType> 
      <xs:simpleContent> 
       <xs:extension base="xs:string"> 
        <xs:attribute ref="qty"/> 
       </xs:extension> 
      </xs:simpleContent> 
     </xs:complexType> 
    </xs:element> 
</xs:schema> 

enter image description here 如何使我的xml文件生效?

回答

1

進行以下更改:

  1. 從根元素刪除xmlns="http://www.tutortutor.ca/"因爲XSD沒有這樣targetNamespace
  2. 變化

    xsi:schemaLocation="http://www.tutortutor.ca/schemas recipe.xsd" 
    

    xsi:noNamespaceSchemaLocation="recipe.xsd" 
    
  3. 修正了XSD錯字:

    <xs:element ref="ingredients" maxOccurs="unbounded"/> 
    

    <xs:element ref="ingredient" maxOccurs="unbounded"/> 
    

然後,根據您的要求,您的XML將對您的XSD有效。