xml入门/jdom

XML(eXtensible Markup Language):可扩展标记语言,描述事物本身

 

Namespace(命名空间)

比如:下面的XML文件

<?xml version="1.0" encoding="gb2312"?>
<policeman
    xmlns="http://www.police.net/policeman.dtd"
    xmlns:X="http://www.police.net/criminal.dtd">
    <name>张三</name>
    <X:criminal>
        <X:name>李四</X:name>
    </X:criminal>
</policeman>

 

这里的<name>就属于"http://www.police.net/policeman.dtd"这个命名空间下,而<X:criminal></X:name>就属于"http://www.police.net/criminal.dtd"这个命名空间下。

 

特殊字符:

> &gt;

< &lt;

& &amp;

" &quot;

' &apos;

XSL(eXtensible Stylesheet Language):展现事务表现形式

icecream.xml文件内容

<?xml version="1.0" encoding="GB2312"?>
<?xml-stylesheet type="text/xsl" href="icecream_search.xsl"?>
<icecream_shop>
    <name>冰激凌专营店</name>
    <icecream>
        <货号>00134679</货号>
        <品名>吃了必吐</品名>
        <价格>75.00</价格>
        <描述页 网址="http://www.icecream.com/ouou.html">详细了解请到这里</描述页>
    </icecream>
    <icecream>
        <货号>00258423</货号>
        <品名>吐了再吃</品名>
        <价格>40.00</价格>
        <描述页 网址="http://www.icecream.com/etet.html">详细了解请到这里</描述页>
    </icecream>
</icecream_shop>

 

icecream_search.xsl文件内容(下面<xsl:value-of select="*/name"/>之类是xsl语法)

<?xml version="1.0" encoding="gb2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/TR/WD-xsl">
    <xsl:template match="/">
    	<html>
    	    <head><title>结果</title></head>
    	    <body>
    	        <div align="center"><p>冰激凌</p></div>
    	        <div align="center"><p>
    	            <xsl:value-of select="*/name"/>
    	        </p></div>
    	    <xsl:apply-templates select="icecream_shop"/>
    	    </body>
    	</html>
    </xsl:template>
    
    <xsl:template match="icecream_shop">
        <p align="center">
        <table border="1">
            <tr>
                <td>货号</td>
    	        <td>品名</td>
    	        <td>价格</td>
    	        <td>描述页</td>
            </tr>
            <xsl:for-each select="icecream">
                <tr>
                    <td><xsl:value-of select="货号"/></td>
                    <td><xsl:value-of select="品名"/></td>
                    <td><xsl:value-of select="价格"/></td>
                    <td>
                        <a>
                            <xsl:attribute name="href">
                                <xsl:value-of select="描述页/@网址"/>
                            </xsl:attribute>
                            <xsl:value-of select="描述页"/>
                        </a>
                    </td>
                </tr>
            </xsl:for-each>
        </table>
        </p>
    </xsl:template>

</xsl:stylesheet>

 

IE打开icecream.xml

 

DTD&Schema:定义XML的语法,约束XML

DTD

book.dtd(现在用的很少了)

<?xml version="1.0" encoding="gb2312"?>
<!ELEMENT books (book*)>
<!-- 元素"book",其下子元素: name(有且仅有一次)、author(至少一个)、price(0个或多个),如果是?的话,表示0个或一个,这里"name,author+,price*"是用逗号隔开,表示显示必须按照这个顺序,如果用空格隔开,表示显示没有顺序 -->
<!ELEMENT book (name,author+,price*)>
<!-- 元素"book"必须有id属性,并且值不能是数字 -->
<!ATTLIST book id ID #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ATTLIST author sex CDATA 'male'>
<!ELEMENT price (#PCDATA)>
<!-- 约束"price"标签中"unit"属性,有三个选择:RMB|dollar|yen,默认RMB -->
<!ATTLIST price unit (RMB|dollar|yen) 'RMB'>

 

book.xml

<?xml version="1.0" encoding="gb2312"?>
<!-- <!DOCTYPE 根元素名 SYSTEM "DTD文件名"> -->
<!DOCTYPE books SYSTEM "book.dtd">
<books>
	<book id="p1">
		<name>萍踪侠影</name>
		<author sex="male">梁羽生</author>
		<price unit="RMB">100.60</price>
	</book>
	<book id="p2">
		<name>岳阳楼记</name>
		<author>范仲淹</author>
		<price unit="dollar">76.8</price>
	</book>
</books>

 

Schema

(1)user.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
		targetNamespace="http://www.example.org/user"
		xmlns:tns="http://www.example.org/user" 
		elementFormDefault="qualified">
	<element name="user">
		<complexType>
			<sequence>
				<element name="id" type="int"/>
				<element name="username" type="string"/>
				<element name="born" type="date"/>
			</sequence>
		</complexType>
	</element>
</schema>

 

user_1.xml

<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="http://www.example.org/user"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.example.org/user">
	<id>1</id>
	<username>张三</username>
	<born>1989-12-02</born>
</user>

 

user_2.xml

<?xml version="1.0" encoding="UTF-8"?>
<user xmlns="http://www.example.org/user"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:noNamespaceSchemaLocation="user.xsd">
	 <id>2</id>
	 <username>李四</username>
	 <born>1988-08-02</born>
</user>

 

(2)books.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
		targetNamespace="http://www.example.org/books"
		xmlns:tns="http://www.example.org/books" 
		elementFormDefault="qualified">
	<element name="books">
		<complexType>
			<!-- maxOccurs表示最大出现次数(unbounded表示无限制) -->
			<sequence maxOccurs="unbounded">
				<element name="book">
					<complexType>
						<sequence minOccurs="1" maxOccurs="unbounded">
							<element name="title" type="string" />
							<element name="content" type="string" />
							<choice>
								<element name="author" type="string" />
								<element name="authors">
									<complexType>
										<all><!-- 表示每个元素只能出现一次 -->
											<element name="author1" type="string"/>
											<element name="author2" type="string"/>
										</all>
									</complexType>
								</element>
							</choice>
						</sequence>
						<attribute name="id" type="int" use="required"/>
					</complexType>
				</element>
			</sequence>
		</complexType>
	</element>
</schema>

 

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<book:books xmlns:book="http://www.example.org/books"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.example.org/books">
	<book:book id="1">
		<book:title>Java in action</book:title>
		<book:content>Java is good</book:content>
		<book:author>Bruce</book:author>
	</book:book>
	<book:book id="2">
		<book:title>SOA in action</book:title>
		<book:content>soa is difficult</book:content>
		<book:authors>
			<book:author1>Jike</book:author1>
			<book:author2>Tom</book:author2>
		</book:authors>
	</book:book>
</book:books>

 

(3)book.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
		targetNamespace="http://www.example.org/book" 
		xmlns:tns="http://www.example.org/book" 
		elementFormDefault="qualified">

	<element name="book" type="tns:bookType"/>
	<element name="id" type="int"/>
	<element name="title" type="string"/>
	<element name="content" type="string"/>
	
	<complexType name="bookType">
		<sequence>
			<element ref="tns:id"/>
			<element ref="tns:title"/>
			<element ref="tns:content"/>
		</sequence>
	</complexType>
</schema>

 

book.xml

<?xml version="1.0" encoding="UTF-8"?>
<book xmlns="http://www.example.org/book"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.example.org/book">
	  <id>1</id>
	  <title>java</title>
	  <content>hello</content>
</book>

 

(4)person.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" 
		targetNamespace="http://www.example.org/person" 
		xmlns:tns="http://www.example.org/person" 
		elementFormDefault="qualified">
		
	<element name="person" type="tns:personType"/>
	
	<complexType name="personType">
		<sequence>
			<element name="name" type="string"/>
			<element name="age" type="tns:ageType"/>
			<element name="email" type="tns:emailType"/>
		</sequence>
		<attribute name="sex" type="tns:sexType"/>
	</complexType>
	
	<simpleType name="ageType">
		<restriction base="int">
			<minInclusive value="1"/>
			<maxExclusive value="150"/>
		</restriction>
	</simpleType>
	
	<simpleType name="emailType">
		<restriction base="string">
			<pattern value="(\w+\.*)*\w+@\w+\.[A-Za-z]{2,6}"/>
			<minLength value="6"/>
			<maxLength value="255"/>
		</restriction>
	</simpleType>
	
	<simpleType name="sexType">
		<restriction base="string">
			<enumeration value="男"/>
			<enumeration value="女"/>
		</restriction>
	</simpleType>
</schema>

 

person.xml

<?xml version="1.0" encoding="UTF-8"?>
<person xmlns="http://www.example.org/person"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.example.org/person" sex="男">
	 <name>张三</name>
	 <age>20</age>
	 <email>zhangsan@126.com</email>
</person>

 

(5)xsd文件包含的使用

student.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
		targetNamespace="http://www.example.org/classroom" 
		xmlns:tns="http://www.example.org/classroom" 
		elementFormDefault="qualified">
		
	<xsd:element name="student" type="tns:studentType"/>
	
	<xsd:complexType name="studentType">
		<xsd:sequence>
			<xsd:element name="name" type="xsd:string"/>
			<xsd:element name="sex" type="tns:sexType"/>
		</xsd:sequence>
	</xsd:complexType>
	
	<xsd:simpleType name="sexType">
		<xsd:restriction base="xsd:string">
			<xsd:enumeration value="男"/>
			<xsd:enumeration value="女"/>
		</xsd:restriction>
	</xsd:simpleType>
</xsd:schema>

 

classroom.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
		targetNamespace="http://www.example.org/classroom" 
		xmlns:tns="http://www.example.org/classroom" 
		elementFormDefault="qualified">
	<xsd:include schemaLocation="student.xsd"/>
	
	<xsd:element name="classroom" type="tns:classroomType"/>
	
	<xsd:complexType name="classroomType">
		<xsd:sequence>
			<xsd:element name="grade" type="tns:gradeType"/>
			<xsd:element name="name" type="xsd:string"/>
			<xsd:sequence minOccurs="1" maxOccurs="unbounded">
				<xsd:element name="student" type="tns:studentType"/>
			</xsd:sequence>
		</xsd:sequence>
	</xsd:complexType>
	
	<xsd:simpleType name="gradeType">
		<xsd:restriction base="xsd:int">
			<xsd:minInclusive value="2000"/>
			<xsd:maxInclusive value="3000"/>
		</xsd:restriction>
	</xsd:simpleType>
</xsd:schema>

 

classroom.xml

<?xml version="1.0" encoding="UTF-8"?>
<classroom xmlns="http://www.example.org/classroom"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.example.org/classroom">
	<grade>2500</grade>
	<name>自习室</name>
	<student>
		<name>张三</name>
		<sex>男</sex>
	</student>
	<student>
		<name>李四</name>
		<sex>女</sex>
	</student>
</classroom>

 

DOM&SAX

DOM:所有数据位于内存。

SAX:流程性分析,不必把所有数据加载到内存中,可分析大型的XML文件,常用于server-sideXML转换。

 

(3)jdom读取xml文件的例子

global-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<sys-config>
	<jdbc-info>
		<driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
		<url>jdbc:mysql://localhost:3306/mydata</url>
		<user-name>root</user-name>
		<password>root</password>
	</jdbc-info>
</sys-config>

 

GlobalConfig.java

package com.test.jdbc;


import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import com.test.jdbc.bean.JDBCInfo;

public class GlobalConfig {

	private static GlobalConfig instance = new GlobalConfig();

	private static final String CONFIG_FILE_NAME = "global-config.xml";

	private Element rootElement;

	private JDBCInfo jdbcInfo = new JDBCInfo();

	public JDBCInfo getJdbcInfo() {
		return jdbcInfo;
	}

	private GlobalConfig() {
		SAXBuilder sb = new SAXBuilder();
		try {
			Document doc = sb.build(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(CONFIG_FILE_NAME));
			rootElement = doc.getRootElement();
			initJDBCInfo();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static GlobalConfig getInstance() {
		return instance;
	}

	public void initJDBCInfo() {
		try {
			Element driverClassName = (Element) XPath.selectSingleNode(rootElement,
					"//sys-config/jdbc-info/driver-class-name");
			jdbcInfo.setDriverClassName(driverClassName.getText());
			Element url = (Element) XPath.selectSingleNode(rootElement,
					"//sys-config/jdbc-info/url");
			jdbcInfo.setUrl(url.getText());
			Element userName = (Element) XPath.selectSingleNode(rootElement,
					"//sys-config/jdbc-info/user-name");
			jdbcInfo.setUserName(userName.getText());
			Element password = (Element) XPath.selectSingleNode(rootElement,
					"//sys-config/jdbc-info/password");
			jdbcInfo.setPassword(password.getText());
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}

}

 

JDBCInfo.java

package com.test.jdbc.bean;

public class JDBCInfo {
	private String driverClassName;

	private String url;

	private String userName;

	private String password;

	public String getDriverClassName() {
		return driverClassName;
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String toString() {
		return "JDBCInfo [driverClassName=" + driverClassName + ", url=" + url + ", userName="
				+ userName + ", password=" + password + "]";
	}

}

 

TestJDBCForGlobalConfig.java

package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.test.jdbc.bean.JDBCInfo;

public class TestJDBCForGlobalConfig {

	public static void main(String[] args) {

		JDBCInfo jdbcInfo = GlobalConfig.getInstance().getJdbcInfo();

		ResultSet rs = null;
		Statement stmt = null;
		Connection conn = null;
		try {
			Class.forName(jdbcInfo.getDriverClassName());
			conn = DriverManager.getConnection(jdbcInfo.getUrl(), jdbcInfo.getUserName(), jdbcInfo.getPassword());
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from dept");
			while (rs.next()) {
				System.out.println(rs.getString("dname") + "	" + rs.getInt("deptno"));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

 

(4)jdom生成xml文件的例子

package com.test.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * <?xml version="1.0" encoding="GB2312"?>
 * <peoples>
 * 		<people>
 * 			<name>张三</name>
 * 			<sex>男</sex>
 * 		</people>
 * 		<people>
 * 			<name>李四</name>
 * 			<sex>女</sex>
 * 		</people>
 * </peoples>
 */
public class XMLWriter {

	public static void main(String[] args) {
		Element peoplesElement = new Element("peoples");
		
		Element peopleElement1 = new Element("people");
		Element nameElement1 = new Element("name");
		nameElement1.addContent("张三");
		Element sexElement1 = new Element("sex");
		sexElement1.addContent("男");
		
		Element peopleElement2 = new Element("people");
		Element nameElement2 = new Element("name");
		nameElement2.addContent("李四");
		Element sexElement2 = new Element("sex");
		sexElement2.addContent("女");

		peopleElement1.addContent(nameElement1);
		peopleElement1.addContent(sexElement1);
		peopleElement2.addContent(nameElement2);
		peopleElement2.addContent(sexElement2);
		
		peoplesElement.addContent(peopleElement1);
		peoplesElement.addContent(peopleElement2);

		Document doc = new Document(peoplesElement);

		XMLOutputter out = new XMLOutputter();
		out.setFormat(Format.getCompactFormat().setEncoding("GB2312"));

		String xml = out.outputString(doc);
		System.out.println(xml);

		try {
			out.output(doc, new FileOutputStream("d:/test.xml"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

注:记得引入jdomjar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值