XML知识1--xml格式熟悉

来源:互联网 发布:easymule 软件 编辑:程序博客网 时间:2024/05/01 20:03

 一.基本认识

这是一个很简单的XML文档,场景是一个网上书店,有很多书,每本书有两个属性,一个是书名[title],一个为是否展示[show],最后还有一项是这些书的拥有者[owner]信息。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <books>
  3.        <book show="yes">
  4.               <title>Dom4j Tutorials</title>
  5.        </book>
  6.        <book show="yes">
  7.               <title>Lucene Studing</title>
  8.        </book>
  9.        <book show="no">
  10.               <title>Lucene in Action</title>
  11.        </book>
  12.        <owner>O'Reilly</owner>
  13. </books>

 

1.整个文档在程序里面称为“Document

 

2.books,book,title,owner 都是 “Element”---元素 。books可以称为根元素。元素下面可以嵌套元 素,比如book元素下面就包含了title元素。

 

3.<book show="yes"> ,元素括起来的show是“Attribute”---属性

 

4.我们可以将Element的基本类似成树的层次来理解。

 

 

二.带校验的xml文档

xml必须遵守一定的格式约束,如果上面的xml片段写成下面这个格式,虽然不存在语法错误,意义就完全不同了(owner会变成某本书的出版社,而不是所有书的拥有者)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <books>
  3.        <book show="yes">
  4.               <title>Dom4j Tutorials</title>
  5.        </book>
  6.        <book show="yes">
  7.               <title>Lucene Studing</title>
  8.        </book>
  9.        <book show="no">
  10.               <title>Lucene in Action</title>
  11.               <owner>O'Reilly</owner>
  12.        </book>
  13. </books>

因此看看我们使用的spring的配置xml吧:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:aop="http://www.springframework.org/schema/aop"
  5.     xmlns:tx="http://www.springframework.org/schema/tx"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
  8.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
  9.     default-autowire="byName" default-lazy-init="true">
  10.     <!-- 可以提供一些全局变量的配置:) -->
  11.     <bean   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  12.         <property name="location"
  13.             value="classpath:globalVariables.properties" />
  14.     </bean>
  15. </beans>

在根元素<beans>中申明了长长的一串.xsd文件,实际是基于Schema的xml验证文档,来约束配置的正确性。

 

下面看struts2的配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE struts PUBLIC
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">
  5. <struts>
  6. </struts>

这是xml标准格式,通过<!DOCTYPE>元素来指定该xml的验证格式。struts2的验证文档为基于dtd的 strts-2.0.dtd。

原创粉丝点击