xml相关

1 篇文章 0 订阅
1 篇文章 0 订阅

一、XMl验证

 1、使用DTD验证XML

demo.dtd

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT books (book*)>
<!ELEMENT book (name,price,authors,gift?)>
<!ATTLIST book ISBN CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT authors (author+)>
<!ELEMENT author (name,nation?)>
<!ELEMENT author.name (#PCDATA)>
<!ELEMENT nation (#PCDATA)>
<!ELEMENT gift (item*)>
<!ELEMENT item (#PCDATA)>

/*   
  
 #REQUIRED 代表属性不可缺省   
 ATTLIST 用于描述属性   
 CDATA 代表属性的数据类型为文本型   
 
 "*"代表子元素可以出现0到多次   
 "+"代表子元素可以出现1到多次   
 "?"代表子元素可以出现一次、也可以不出现   
   如果没有修饰,代表子元素必须出现1次。   

*/  

 

dtdToXml.xml 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "demo.dtd">	<!-- <!DOCTYPE 根元素名  SYSTEM DTD文件路径-->
<books>
	<book ISBN="5197-5742-5657">
		<name>Java编程思想</name>
		<price>91.5</price>
		<authors>
			<author>
				<name>汤姆斯</name>
				<nation>美国</nation>
			</author>
			<author>
				<name>杰西姆</name>
				<nation>美国</nation>
			</author>
		</authors>
		<gift/>
	</book>
	<book ISBN="8795-4547-7519">
		<name>深入浅出AJAX</name>
		<price>88.0</price>
		<authors>
			<author>
				<name>刘美美</name>
				<nation>中国</nation>				
			</author>
		</authors>
		<gift>
			<item>主题T-shirt</item>
			<item>水杯</item>
		</gift>
	</book>
</books>

2、使用SCHEMA验证XML

book.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
	<xs:element name="books">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="book" minOccurs="0" maxOccurs="unbounded">
					<xs:complexType>
						<xs:sequence>
							<xs:element name="name"/>
							<xs:element name="price"/>
							<xs:element name="authors">
								<xs:complexType>
									<xs:sequence>
										<xs:element name="author" maxOccurs="unbounded">
											<xs:complexType>
												<xs:sequence>
													<xs:element name="name"/>
													<xs:element name="nation" minOccurs="0"/>
												</xs:sequence>
											</xs:complexType>
										</xs:element>
									</xs:sequence>
								</xs:complexType>
							</xs:element>
							<xs:element name="gift" minOccurs="0">
								<xs:complexType>
									<xs:sequence>
										<xs:element name="item" minOccurs="0" maxOccurs="unbounded"/>
									</xs:sequence>
								</xs:complexType>
							</xs:element>
						</xs:sequence>
						<xs:attribute name="ISBN" use="required"/>
					</xs:complexType>
				</xs:element>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>

 

schemaToXml.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="books.xsd">
<book ISBN="5197-5742-5657">
		<name>Java编程思想</name>
		<price>91.5</price>
		<authors>
			<author>
				<name>汤姆斯</name>
				<nation>美国</nation>
			</author>
			<author>
				<name>杰西姆</name>
				<nation>美国</nation>
			</author>
		</authors>
		<gift/>
	</book>
	<book ISBN="8795-4547-7519">
		<name>深入浅出AJAX</name>
		<price>88.0</price>
		<authors>
			<author>
				<name>刘美美</name>
				<nation>中国</nation>				
			</author>
		</authors>
		<gift>
			<item>主题T-shirt</item>
			<item>水杯</item>
		</gift>
	</book>
</books>
<!--
 
	1、若SCHEMA中没有指定目标命名空间(targetNamespace,可以在SCHEMA文件的根元素中指定),则在XML的根元素中通过noNamespaceSchemaLocation属性指定SCHEMA文件的位置,如下例:	
						 schema命名空间															   schema文件位置	
	   <books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="books.xsd">
	2、若SCHEMA中指定了目标命名空间(如http://www.mySchema.com <targetNamespace="http://www.mySchema.com">),则在XML的根元素中通过schemaLocation属性指定SCHEMA文件的位置   
	                                                                                目标命名空间+空格+schema文件位置                               默认命名空间
	   <books xsi:schemaLocation="http://www.mySchema.com books.xsd" xmlns="http://www.mySchema.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	   
 -->

 

二、DOM解析XML与HTML

 1、使用DOM解析XML

以dtdToXml.xml为例   

<<<<script type="text/javascript">
		var xmlDoc=xmlData.XMLDocument;	//获取XML文档
		var root=xmlDoc.documentElement;	//根元素
		var bookA=root.firstChild;	//第一个book元素
		var ISBNValue=bookA.getAttribute("ISBN");	//ISBN属性
		alert('ISBN属性 ='+ISBNValue);
		var bookAChildren=bookA.childNodes;	//book子元素
		var name=bookAChildren[0];	//name元素
		alert(name.nodeType);
		alert(name.nodeName);
		alert(name.nodeValue);
		var text=name.firstChild;	//name中文本节点
		alert(text.nodeType);
		alert(text.nodeName);
		alert(text.nodeValue);
		var authors=name.nextSibling.nextSibling;
		var authorName=authors.firstChild.firstChild.firstChild;
		alert('第一位作者姓名='+authorName.nodeValue);
		var bookB=root.lastChild;
		var bookBParent=bookB.parentNode;
		alert('是否为根元素='+(root==bookBParent));
		
	 /*
	  * 从上例可以看出,按照结构层次进行DOM操作可以一层一层的读出XML文档中的所有内容,但是代码比较繁琐,如果需要快速定位元素,
	  * 可以使用DOM提供的getElementsByTagName方法,根据标签名查找元素。
	  * 下例使用getElementsByTagName方法查找第一本书的信息:
	  * */
	 	var xmlDoc=xmlData.XMLDocument;
	 	var bookA=xmlDoc.getElementsByTagName("book")[0];	//获取所有名为book的元素  保留第一个
		var name=bookA.getElementsByTagName("name")[0];		//获取第一本书的书名
		var price=bookA.getElementsByTagName("price")[0];	
		var names=bookA.getElementsByTagName("authors")[0].getElementsByTagName("name");	//获取第一本书所有的作者名称
		alert('书名='+name.firstChild.nodeValue);	//读取文本内容
		alert('价格='+price.firstChild.nodeValue);
		for(var i=0;i<names.length;i++){
			alert('作者=:'+names[i].firstChild.nodeValue);
		}
</script>

 

 

  2、使用DOM解析HTML  

<script type="text/javascript">
		function demo(){
		  var inputs=document.getElementsByTagName('input');	//document为文本对象
		  alert('<INPUT>元素数量='+inputs.length);
		  var checkboxes=document.getElementsByName('check');
		  for(var i=0;i<checkboxes.length;i++){
			  alert(checkboxes[i].getAttribute('value'));	//获取复选框的属性值
		  }
		}
</script>


<body οnlοad="demo();">
	  <form name="f">
	  	输入框:<input type="text" value="tom"/><br/>
	  	多选框:<input type="checkbox" name="check" value="1"/>
	  	<input type="checkbox" name="check" value="2">
	  </form>
</body>

 

例1:

     使用DOM中的方法在HTML页面上创建一个2x2表格

 

<script type="text/javascript">
		function demo(){
		 var body=document.documentElement.lastChild;	//获取body的对象
		 var table=document.createElement("TABLE");	//必须通过document对象创建元素
		 var tbody=document.createElement("TBODY");
		 var tr=document.createElement("TR");
		 var tdA=document.createElement("TD");
		 var tdAtext=document.createTextNode("单元A");
		 tdA.appendChild(tdAtext);	//子节点必须追加到父节点中
		 var tdB=tdA.cloneNode(true);	//复制单元格
		 tdB.firstChild.nodeValue="单元B";	//修改单元格的文本值
		 tr.appendChild(tdA);
		 tr.appendChild(tdB);
		 tbody.appendChild(tr);
		 tbody.appendChild(tr.cloneNode(true));
		 table.appendChild(tbody);	
		 table.setAttribute("border",1);	//修改边框属性
		 body.appendChild(table);	//必须将表格附加在body中才能在页面显示
</script>

 

例2:

     制作一个具有动态效果的例子:实现商品选择功能,使用者点击“未选中的商品”栏中的商品图片后,将图片移至“选中的商品”栏中,反之亦然。

<script type="text/javascript">
	 function init(){
		 //将10张图片放大未选中商品栏
		 var unSle=document.getElementById("unSelect");
		 for(var i=1;i<=10;i++){
			 var img=document.createElement('IMG');
			 img.setAttribute("src","imgs/"+i+".png");
			 //为图片增加点击事件,img_onclick为方法名
			 img.setAttribute("onclick",img_onclick);
			 unSle.appendChild(img);
		 }
	 }
	 
	 //图片的事件处理方法
	 function img_onclick(){
		 var unSel=document.getElementById("unSelect");
		 var sel=document.getElementById("selected");
		 //判断当前被点击图片的父节点是哪一个
		 if(this.parentNode == unSel){
			 //如果父节点是入"未选中商品栏",则将图片移至"选中商品栏"
			 sel.appendChild(this);
		 }else{
			 unSel.appendChild(this);
		 }
	 }
</script>

<body οnlοad="init();">
   	<h3>未选中的商品</h3>
   	<div id="unSelect"></div>
   	<h3>选中的商品</h3>
   	<div id="selected"></div>
</body>

  

三、JDOM

1、JAXP对XML的操作

emps.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<emps>
    <emp empId="1">
        <name>张三</name>
        <sex>男</sex>
        <telephone>1351234567</telephone>
        <birthday>1986-04-16T00:00:00+08:00</birthday>
        <dept>培训部</dept>
        <favs>足球,篮球</favs>
    </emp>
    <emp empId="2">
        <name>小美</name>
        <sex>女</sex>
        <telephone>1359874561</telephone>
        <birthday>1989-11-12T00:00:00+08:00</birthday>
        <dept>市场部</dept>
        <favs>音乐,电影</favs>
    </emp>
</emps>

 

JaxpToXml.java

package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.omg.PortableInterceptor.AdapterStateHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * jaxp对xml的操作
 * @author Administrator
 *
 */
public class JaxpToXml {
	
	//案例:对上面xml文件进行dom解析,修改empId=2的联系电话,并添加阿聪的信息。  
	public static void main(String[] args) {
		DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder=builderFactory.newDocumentBuilder();
			//获取Document对象。
			Document doc=builder.parse(new File("src/test/emps.xml"));
			//document. getDocumentElement():获取XML文件的根节点,也就是DOM的根节点。
			Element root=doc.getDocumentElement();
			NodeList empList=root.getChildNodes();
			for(int i=0;i<empList.getLength();i++){
				//由于xml文件是格式化的,带有空格和回车换行符,JAXP把这些字符也解析为一个文本节点(CharacterData),此处在遍历XML文件的节点时,需要把Element元素检索出来。
				if(!(empList.item(i) instanceof Element)){
					continue;
				}
				
				Element emp=(Element) empList.item(i);
				//emp.getAttribute("empId")就是获取emp节点的empId属性。
				if(!"2".equals(emp.getAttribute("empId"))){
					continue;
				}
				
				NodeList nodeList=emp.getChildNodes();
				for(int j=0;j<nodeList.getLength();j++){
					if(!(nodeList.item(j) instanceof Element)){
						continue;
					}
					Element element=(Element) nodeList.item(j);
					System.out.println(element.getFirstChild());
					//getNodeName()和getNodeValue()能够获取节点的名称和值,在元素节点中,nodeName就是元素的标签名称,nodeValue没有意义,在文本节点中,nodeValue就是节点的文本,nodeName没有意义,在属性节点中nodeName和nodeValue分别代表属性的名称和属性的值。
					if(element.getNodeName().equals("telephone")){
						//element.setTextContent("文本"),为元素节点添加文本子节点。
						element.setTextContent("13636732076");
						break;
					}
				}
			}

			//document.createElement("节点名称"),根据指定的节点名称创建一个元素节点。
			Element acong=doc.createElement("emp");
			acong.setAttribute("empId", "3");
			
			Element name = doc.createElement("name");
			name.setTextContent("阿聪");
			
			Element sex = doc.createElement("sex");
			sex.setTextContent("男");
			
			Element tel=doc.createElement("telphone");
			tel.setTextContent("13120552106");
			
			Element birthday=doc.createElement("birthday");
			birthday.setTextContent("1986-11-12");
			
			Element favs=doc.createElement("favs");
			favs.setTextContent("足球,美术");
			
			//element.appendChild(子节点),在一个元素节点的子节点列表最后,追加一个子节点。
			acong.appendChild(name);
			acong.appendChild(sex);
			acong.appendChild(tel);
			acong.appendChild(birthday);
			acong.appendChild(favs);
			
			//在根节点最后添加子节点。
			root.appendChild(acong);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

2、JDOM对XML的操作

JdomToXml.java 

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * JDOM对xml的操作 (需要jdom.jar)
 * @author Administrator
 *
 */
public class JdomToXml {
	public static void main(String[] args) {
		/*
		 * 获取SAX解析器,在JDOM中可以使用SAX解析器对XML进行解析、也可以使用DOM解析器进行解析,
		 * 解析的结果都会生成一棵节点树(Document对象),由JDOM进行维护,SAX解析器解析速度比DOM解析器快。
		 * 由于JDOM生成的节点树与W3C的DOM无关,因此普遍使用SAX解析器对XML进行解析。
		 * */
		SAXBuilder builder=new SAXBuilder();
		File xmlFile=new File("src/test/emps.xml");
		try {
			//解析器的build(File)方法可以根据一个xml文件解析出Document对象。
			Document doc=builder.build(xmlFile);
			//Document对象的getRootElement()方法得到根节点。
			Element root=doc.getRootElement();
			//getChildred()方法可以获取某元素节点下的所有子节点。
			List<Element> list=root.getChildren();
			for(Element element:list){
				if("2".equals(element.getAttributeValue("empId"))){
					//setText(text)方法可以设置某元素的文本值
					element.getChild("telephone").setText("13100000000");
					break;
				}
			}
			//创建新元素
			Element emp=new Element("emp");
			emp.setAttribute("empId", "3");
			Element name=new Element("name");
			name.setText("阿聪");
			//添加子节点。可以把创建子节点、设置子节点、添加子节点三个操作同时操作
			emp.addContent(name);
			emp.addContent(new Element("sex").setText("男"));
			emp.addContent(new Element("telephone").setText("13222222222"));
			emp.addContent(new Element("birthday").setText("1988-01-01"));
			emp.addContent(new Element("favs").setText("音乐,美术"));
			root.addContent(emp);
			//创建一个输出器
			XMLOutputter xmlPutter=new XMLOutputter();
			//设置输出格式是友好格式(带换行、缩紧的格式),默认格式是紧凑格式
			xmlPutter.setFormat(Format.getPrettyFormat());
			//Documen输出
			xmlPutter.output(doc, new FileOutputStream(xmlFile));
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

 

3、XPath

bookstore.xml 

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
	<book category="COOKING">
		<title lang="en">Everyday Italian</title>
		<author>Giada De Laurentiis</author>
		<year>2005</year>
		<price>30.00</price>
	</book>
	<book category="CHILDREN">
		<title lang="en">Harry Potter</title>
		<author>J K. Rowling</author>
		<year>2005</year>
		<price>29.99</price>
	</book>
	<book category="WEB">
		<title lang="en">XQuery Kick Start</title>
		<author>James McGovern</author>
		<author>Per Bothner</author>
		<author>Kurt Cagle</author>
		<author>James Linn</author>
		<author>Vaidyanathan Nagarajan</author>
		<year>2003</year>
		<price>49.99</price>
	</book>
</bookstore>

 

JdomXPathToXml.java 

package test;

import java.io.File;
import java.io.IOException;
import java.util.List;

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

/**
 * jdom的XPath方式对xml的操作(需要jaxen.jar,jdom.jar)
 * @author Administrator
 *
 */
public class JdomXPathToXml {

	/*
	 * 案例:用JDom解析上面xml文件,找出book节点category属性的值为WEB的节点的作者信息,
	 * 使用的XPath表达式为:/bookstore/book[@category='WEB']/author
	 * */
	public static void main(String[] args) {
		SAXBuilder builder=new SAXBuilder();
		try {
			File xmlFile=new File("src/test/bookstore.xml");
//			File xmlFile=new File("e:/xml/bookstore.xml");
			Document doc=builder.build(xmlFile);
			//生成一个XPath对象,该对象可以重复使用
			XPath xpath=XPath.newInstance("/bookstore/book[@category='WEB']/author");
			//使用XPath对象对XML进行查询
			List list=xpath.selectNodes(doc);
			for(Object obj:list){
				Element author=(Element)obj;
				System.out.println(author.getText());
			}
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	


}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值