日期:2008-11-21  浏览次数:20412 次

基本XML

讨论xml文件以前我们先看一个例子:

<person>

Alan Turing

</person>

这就是一个标记完好的xml文件,<person>和</person>分别是开始标记和结束标记。

l 开始标记:以<开始,以>结束,中间是标记名称。

l 结束标记:以</开始,以>结束,中间是标记名称。

注意:开始标记和结束标记对应的标记名称必须相同,但是具体使用什么作为名称就没有规定,这个和html是不同的(html的标记名是若干个确定的),你可以使用person来标记一个人,使用cat来标记一只猫。

标记中间的Alan Turing就是数据,其中Alan和Turing之间的空格也是数据,也就是说标记里面的数据中的空格不会别忽略。

有时候我们也许需要没有任何数据的元素(元素指开始标记和结束标记之间的内容,包含开始标记和结束标记,比如上面提到的例子就是一个元素),例如下面的:

<person></person>

这是一个空标记,但是我们有另外更简捷的标记表示空标记:

<person/>

注意:xml是区分大小写的,这与html不同。<Person>和<PERSON>是不同标记,比如你有一个元素以<person>开始,那么你就不能使用</ Person >作为结束标记。

上面的例子指含有一个元素,我们现在给出一个复杂点的例子,然后给出xml树的概念。

<person>
<name>

<first_name>Alan</first_name>

<last_name>Turing</last_name>

</name>

<profession>computer scientist</profession>

<profession>mathematician</profession>

<profession>cryptographer</profession>

</person>

显然上面的例子外层仍然是一个person元素,但是与先前不同的是这个元素含有4个子元素,1个name元素和3个profession元素。我们称person是name的父元素,显然他也是profession的父元素,同样我们可以看到name是first_name和last_name的父元素。

上面的例子我们发现标记进行了嵌套,这是允许的。但是重叠标记是非法的,比如:
<strong><em>this common example from HTML</strong></em>

应该是:

<strong><em>this common example from HTML</em></strong>

根据上面的例子中父子元素的关系以及注意到任何xml文件只能且只能含有一个根元素(也就是没有父元素的元素)看起来很象一个树,如图:




现在我们给出一个混合数据的xml文件的例子,

<biography>
<name><first_name>Alan</first_name> <last_name>Turing</last_name>
</name> was one of the first people to truly deserve the name
<emphasize>computer scientist</emphasize>. Although his contributions
to the field are too numerous to list, his best-known are the
eponymous <emphasize>Turing Test</emphasize> and
<emphasize>Turing Machine</emphasize>.

<definition>The <term>Turing Test</term> is to this day the standard
test for determining whether a computer is truly intelligent. This
test has yet to be passed. </definition>

<definition>The <term>Turing Machine</term> is an abstract finite
state automaton with infinite memory that can be proven equivalent
to any any other finite state automaton with arbitrarily large memory.
Thus what is true for a Turing machine is true for all equivalent
machines no matter how implemented.
</definition>

<name><last_name>Turing</last_name></name> was also an accomplished
<profession>mathematician</profession> and
<profession>cryptographer</profession>. His assistance
was crucial in helping the Allies decode the German Enigma
machine. He committed suicide on <date><month>June</month>
<day>7</day>, <year>1954</year></date> after being
convicted of homosexuality and forced to take female
hormone injections.
</biography>
上面的例子我不作解释,但是你要知道他是一个合法的xml文件,也就是说标记和内容可以混排。但是这样格式的xml文件在程序的处理上就很麻烦,所以不推荐使用。

接着我们谈谈属性(Attributes)。看例子:

<person born="1912-06-23" died="1954-06-07">

Alan Turing

</person>

其中红色标记的born和died就是属性。其中born是属性名,1912-06-23是属性值,属性值是用”筐起来的,当然也可以用单引号’筐起来。

<person died = '1954-06-07' born = '1912-06-23' >

Alan Turing

</person>

使用单引号的作用是你可以在属性的值里面添加双引号。

到这里我们发现一个问题:

<person>

<name first