---
title: "转载：XML头里standalone的作用"
author: "codermouse"
date: "2011-02-16T11:34:56Z"
tags: []
categories: ["编程语言"]
slug: "xml-standalone"
draft: false
lastmod: "2011-02-16T11:34:56Z"
id: 907688
url: "https://codermouse.iteye.com/blog/907688"
---

今天在看用TdataSet生成的XML中第一行里有个standalone,不知道是什么意思,查了一下资料才知道它的作用,下面就把我了解的写下来.

standalone  用来表示该文件是否呼叫其它外部的文件。若值是 ”yes” 表示没有呼叫外部文件，若值是 ”no” 则表示有呼叫外部文件。默认值是 “yes”。

这里所指的外部文件其实就是查检XML是不是有效的约束文件,或是DTD或是Schema,那这两者又有什么区别呢?

   尽管XML1.0提供了一种机制，即文档类型定义（DTD）来规范XML的格式规则。但是它天生存在一些缺点，比如，它采用了非XML的语法规则、不支持更多的数据类型、扩展性差等，为了克服这些缺点，XML Schema 出现了。W3C推荐在XML中使用XML Schema来代替DTD。
XML Schema（模式） 跟DTD一样，也用于定义 XML 文档的约束。但它与DTD明显不同的是，XML Schema遵循XML语法规则，更好地支持数据类型以及命名空间。W3C称：XML Schema is an XML based alternative to DTD。模式在单独的文件中定义，通常扩展名为 .xsd。每个模式定义都有一个根元素 schema，该元素属于名称空间http://www.w3.org/2001/XMLSchema。schema 元素可以包含可选的属性。比如：
<xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema
    elementFormDefault="qualified" attributeFormDefault="unqualified">
这表示模式中使用的元素来自http://www.w3.org/2001/XMLSchema名称空间。
XML 文件使用 schema 名称空间中的 schemaLocation 属性链接到对应的模式。使用 schemaLocation 属性必须定义 schema 名称空间。所有这些定义都出现在 XML 文档的根元素中。语法如下：
<root_element  schema_namespace_definition  schema_location_definition>
下面是一个例子：
<Books  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
 xs:schemaLocation="http://www.example.com Books.xsd">
先来看看一个XML文件示例（message.xml），分别用DTD和XML Schema 描述这个文件，看看它们之间的区别：

1、使用DTD：

> <?xml version="1.0" standalone="yes"?>
> <!DOCTYPE message[
>   <!element message (to,from,body)>
>   <!element to      (#pcdata)>
>   <!element from    (#pcdata)>
>   <!element body    (#pcdata)>
> ]>
> <message>
>   <to>rose</to>
>   <from>alex</from>
>   <body>Hi,My Girl!</body>
> </message>


2、使用XML Schema ：

message.xml:

```java

<?xml version="1.0" standalone="no"? >
<message xmlns=http://www.example.com 
  xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance 
  xsi:schemaLocation="http://www.example.com message.xsd">
   <to>Rose</to>
   <from>Alex</from>
   <body>Hi,My Girl!</body>
</message>
```

message.xsd:

```java
<?xml version="1.0"?>
<xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema 
targetNamespace=http://www.example.com 
xmlns="http://www.example.com" elementFormDefault="qualified">
 <xs:element name="message">
  <xs:complexType>
    <xs:sequence>
    <xs:element name="to" type="xs:string"/>
    <xs:element name="from" type="xs:string"/>
    <xs:element name="body" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
 </xs:element>
</xs:schema>
```


来源：http://lyjgs.168.blog.163.com/blog/static/7650077820084763435588/