??xml version="1.0" encoding="utf-8" standalone="yes"?> 下面的XPath表达式选择ROOT元素order /order 下面的XPath表达式选择元素order中的所有item元素 /order/item 下面的XPath表达式选择元素order下元素item中的所有price元素 注释Q用“/”路径开始代表元素的l对路径 下面的XPath表达式选择元素item中的所有price值大?2.60的元?br />
/order/item[price>12.60] 节点定位Q?/p>
XML文挡可以表示为树(wi)l构节点形式 一个XPath的模式是使用反斜?#8220;/”分开子元素名U描q\?/p>
下面的XPath表达式选择元素order下元素item中的所有price元素 注释Q用“/”路径开始代表元素的l对路径. 不用“/”路径开始代表元素的相对路径 item/price ?#8220;//”路径开始代表整个文档满x(chng)件的所有元?/p>
下面的XPath表达式选择文档中所有的item元素 选择未知元素 通配W?nbsp;“*”可用于选择未知XML元素 下面的XPath表达式选择元素order中的所有item元素所属的子元?/p>
/order/item/* 下面的XPath表达式选择元素order下所有孙子辈的price元素 下面的XPath表达式选择所有具有两个祖先的price元素 下面的XPath表达式选择文档所有元?br />
//* 选择分支 使用Ҏ(gu)号[]可以指定特定的元?/p>
下面的XPath表达式选择元素order中的W一个item的子元素 /order/item[1] 下面的XPath表达式选择元素order中的最后一个item的子元素 下面的XPath表达式选择元素order中具有price元素的item元素 下面的XPath表达?从元素order中选择hprice{于12.60元素的item元素 下面的XPath表达?从隶属于元素order的item元素中选择hprice{于12.60元素的price元素 选择几个路径 在XPath表达式中Q?nbsp;"|" q算W可以选择几个路径 。实质上是逻辑“?#8221;操作 下面的XPath表达?从隶属于order的item元素中选择所有itemNumber 和description 元素 下面的XPath表达?从文档中选择所有itemNumber Qdescription和price 元素 下面的XPath表达?选取属于order中item下所有itemNumber元素和从文档中选择所有description元素 选择属?br />
在XPath中,所有属性用@前缀 下面的XPath表达?选取所有名为catalog的属?br />
//@catalog 下面的XPath表达?选取所有具有Q何属性的item元素 下面的XPath表达?选取所有具有catalog{于"parts"属性的item元素
import net.sf.json.*;
import java.util.*;
import domain.*;
public class JsonDemo {
public static void arraytojson(){
String[] kkname={"CCED","WPS","WORD"};
JSONArray jr=JSONArray.fromObject(kkname);
System.out.println(jr);
}
public static void list2json(){
List<Book> bklist=new ArrayList<Book>();
bklist.add(new Book("a1","b","111"));
bklist.add(new Book("a2","b","111"));
bklist.add(new Book("a3","_NJAVA","111"));
JSONArray jr=JSONArray.fromObject(bklist);
System.out.println(jr);
}
public static void createJson(){
JSONArray jn=JSONArray.fromObject("[{bookname:'JAVAE序设计',isbn:'885596-99',author:'东'}]");//开头和l尾带[]
List a=JSONArray.toList(jn, Book.class);
Book book=null;
for(Iterator it=a.iterator();it.hasNext();){
book=(Book)it.next();
System.out.println(book.getAuthor()+"-"+book.getBookname());
}
}
public static void Map2Json(){
Map map=new HashMap();
map.put("name", "裴");
map.put("book", new Book("K语言E序设计","?/span>","55588"));
map.put("shoBookName","function(){alert('试')}");
JSONObject jo=JSONObject.fromObject(map);
System.out.println(jo);
}
public static void bean2json(){
JSONObject jo=JSONObject.fromObject(new Book("1","3","ABCd"));
System.out.println(jo);
}
public static void json2bean(){
JSONObject jo=JSONObject.fromObject("{bookname:'C++E序设计',isbn:'885596-989',author:'东'}");
Book book=(Book)JSONObject.toBean(jo,Book.class);
System.out.println(book.getAuthor()+"-"+book.getBookname());
}
public static void main(String[] args)throws Exception{
arraytojson();
list2json();
createJson();
Map2Json();
json2bean();
}
}
]]>
]]>
<order>
<item>
<itemNumber>C2688-67037</itemNumber>
<description>LCD液晶昄?/span></description>
<quantity>1</quantity>
<price>358.00</price>
</item>
<item>
<itemNumber>C2688-67061</itemNumber>
<description>音箱</description>
<quantity>1</quantity>
<price>16.50</price>
</item>
<item>
<itemNumber>C2688-67010</itemNumber>
<description>鼠标</description>
<quantity>1</quantity>
<price>8.50</price>
</item>
</order>
/order/item/price
XPath定义标准函数?/p>
XPath使用模式表达式识别XML文档的节炏V?/p>
/order/item/price
//item
/order/*/price
/*/*/price
/order/item[last()]
/order/item[price]
/order/item[price=16.50]
/order/item[price=16.50]/price
/order/item/itemNumber | /order/item/description
下面的XPath表达?从文档中选择所有itemNumber 和description 元素
//itemNumber | //description
//itemNumber | //description | //price
/order/item/itemnumber | //description
下面的XPath表达?选取所有具有catalog属性的item元素
//item[@catalog]
//item[@*]
//item[@catalog="parts"]
]]>
www.w3pop.comq网站上有与XML/HTML相关的详l资料?br />
在Myeclipse~写XSD文g非常的主法,只需要把与XSD相关的元素记住就行,像编辑XML一Pq且有提C,q可以根据XSD文g建立XML文g。这是一个随便写的XSD文g
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/note" xmlns:tns="http://www.example.org/note">
<element name="note">
<complexType>
<attribute name="id" type="integer" use="required" />
<sequence>
<element name="to" >
<simpleType>
<restriction base="integer">
<minInclusive value="0"></minInclusive>
<maxInclusive value="100"></maxInclusive>
</restriction>
</simpleType>
</element>
<element name="from" type="string"/>
<element name="heading" type="string"/>
<element name="body" type="string"/>
</sequence>
</complexType>
</element>
</schema>
]]>
http://www.aygfsteel.com/huanghuizz/articles/142875.html json in java的介l?br />
一json学习(fn)好文
http://wangcheng.javaeye.com/blog/71343
]]>
Java提供?jin)SAX和DOM两种方式用于解析XML,但即便如?要读写一个稍微复杂的XML,也不是一件容易的?
二、XMLBean?/p>
Hibernate已经成ؓ(f)目前行的面向Java环境的对?关系数据?/font>映射工具.在Hibernate{对?关系数据库映工具出C?Ҏ(gu)据库的操作是通过JDBC来实现的,Ҏ(gu)据库的Q何操?开发h员都要自己写SQL语句来实? 对象/关系数据库映工具出现后,Ҏ(gu)据库的操作{成对JavaBean的操?极大方便?jin)数据库开? 所以如果有一个类似的工具能够实现对XML的读写{成对JavaBean的操?会(x)化XML的读?即对XML不熟(zhn)的开发h员(sh)能方便地dXML. q个工具是XMLBean.
三、准备XMLBean和XML文档
XMLBean是Apache的一个开源项?可以?a snap_preview_added="spa" snap_icon_added="spa" act_suffix="" icon_trigger="false" text_trigger="true" parent_link_icon="false">http://www.apache.org下蝲,最新的版本?.0. 解压后目录如?
xmlbean2.0.0
+---bin
+---docs
+---lib
+---samples
+---schemas
另外q要准备一个XML文档(customers.xml),
在本文的例子?我们对q个文档q行d操作. 文档源码如下:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<customer>
<id>1</id>
<gender>female</gender>
<firstname>Jessica</firstname>
<lastname>Lim</lastname>
<phoneNumber>1234567</phoneNumber>
<address>
<primaryAddress>
<postalCode>350106</postalCode>
<addressLine1>#25-1</addressLine1>
<addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
</primaryAddress>
<billingAddress>
<receiver>Ms Danielle</receiver>
<postalCode>350107</postalCode>
<addressLine1>#167</addressLine1>
<addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
</billingAddress>
</address>
</customer>
<customer>
<id>2</id>
<gender>male</gender>
<firstname>David</firstname>
<lastname>Bill</lastname>
<phoneNumber>808182</phoneNumber>
<address>
<primaryAddress>
<postalCode>319087</postalCode>
<addressLine1>1033 WS St.</addressLine1>
<addressLine2>Tima Road</addressLine2>
</primaryAddress>
<billingAddress>
<receiver>Mr William</receiver>
<postalCode>672993</postalCode>
<addressLine1>1033 WS St.</addressLine1>
<addressLine2>Tima Road</addressLine2>
</billingAddress>
</address>
</customer>
</Customers>
q是一个客L(fng)数据模型,每个客户都有客户~号(ID),姓名,性别(gender),?sh)话L(fng)(phoneNumber)和地址,其中地址有两? 首要地址(PrimaryAddress)和帐单地址(BillingAddress),每个地址有邮~?地址1,和地址2l成.其中帐单地址q有收g?receiver).此外,q要准备一个配|文?文g名customer.xsdconfig),q个文g的作用我后面?x)?它的内容如下:
<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config">
<xb:namespace>
<xb:package>sample.xmlbean</xb:package>
</xb:namespace>
</xb:config>
四、XMLBean使用步骤
和其他面向Java环境的对?关系数据库映工L(fng)使用步骤一?在正式用XMLBean?我们要作两个准备.
1. 生成XML Schema文g
什么是XML Schema文g? 正常情况?每个XML文g都有一个Schema文g,XML Schema文g是一个XML的约束文?它定义了(jin)XML文g的结构和元素.以及(qing)对元素和l构的约? 通俗地讲,如果说XML文g是数据库里的记录,那么Schema是表结构定?
Z么需要这个文? XMLBean需要通过q个文g知道一个XML文g的结构以?qing)约?比如数据cd{? 利用q个Schema文g,XMLBean会(x)产生一pd相关的Java Classes来实现对XML的操? 而作为开发h?则是利用XMLBean产生的Java Classes来完成对XML的操作而不需要SAX或DOM.怎样产生q个Schema文g? 如果对于熟?zhn)XML的开发h?可以自己来写q个Schema文g,对于不熟(zhn)XML的开发h?可以通过一些工h完成.比较有名的如XMLSPY和Stylus Studio都可以通过XML文g来生成Schema文g. 加入我们已经生成q个Schema文g(customer.xsd):
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="Customers">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="customer"
type="customerType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="customerType">
<xs:sequence>
<xs:element name="id" type="xs:int"/>
<xs:element name="gender" type="xs:string"/>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="phoneNumber" type="xs:string"/>
<xs:element name="address" type="addressType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="addressType">
<xs:sequence>
<xs:element name="primaryAddress" type="primaryAddressType"/>
<xs:element name="billingAddress" type="billingAddressType"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="primaryAddressType">
<xs:sequence>
<xs:element name="postalCode" type="xs:string"/>
<xs:element name="addressLine1" type="xs:string"/>
<xs:element name="addressLine2" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="billingAddressType">
<xs:sequence>
<xs:element name="receiver" type="xs:string"/>
<xs:element name="postalCode" type="xs:string"/>
<xs:element name="addressLine1" type="xs:string"/>
<xs:element name="addressLine2" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
2. 利用scomp来生成Java Classes
scomp是XMLBean提供的一个编译工?它在bin的目录下. 通过q个工具,我们可以以上的Schema文g生成Java Classes.scomp的语法如?-
scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
主要参数说明:
-src [dir] -- 生成的Java Classes存放目录
-srconly -- 不编译Java Classes,不生Jar文g
-out [jarFileName] -- 生成的Jar文g,~省是xmltypes.jar
-compiler -- Java~译器的路径,即Javac的位|?/p>
schemaFile.xsd -- XML Schema文g位置
config.xsdconfig -- xsdconfig文g的位|? q个文g主要用来制定生成的Java Class的一些文件名规则和Package的名U?在本?package是sample.xmlbean
在本?我是q样q行?
scomp -src build\src -out build\customerXmlBean.jar schema\customer.xsd
-compiler C:\jdk142_04\bin\javac customer.xsdconfig
q个命o(h)行的意思是告诉scomp生成customerXmlBean.jar,攑֜build目录?同时生成源代码放在build\src? Schema文g是customer.xsd,xsdconfig文g是customer.xsdconfig.其实, 生成的Java源代码没有多大作?我们要的是jar文g.我们先看一下build\src\sample\xmlbean下生成的Classes.
CustomersDocument.java -- 整个XML文档的Java Class映射
CustomerType.java -- 节点sustomer的映?/p>
AddressType.java -- 节点address的映?/p>
BillingAddressType.java -- 节点billingAddress的映?/p>
PrimaryAddressType.java -- 节点primaryAddress的映?/p>
好了(jin),到此我们所有的准备工作已经完成? 下面开始进入重?利用刚才生成的jar文gdXML.
五、利用XMLBean读XML文g
新徏一个Java Project,XMLBean2.0.0\lib\下的Jar文g和刚才我们生成的customerXmlBean.jar加入到Project的ClassPath.
新徏一个Java Class: CustomerXMLBean. 源码如下:
package com.sample.reader;
import java.io.File;
import sample.xmlbean.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.xmlbeans.XmlOptions;
public class CustomerXMLBean {
private String filename = null;
public CustomerXMLBean(String filename) {
super();
this.filename = filename;
}
public void customerReader() {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
println("Customer#" + i);
println("Customer ID:" + customer.getId());
println("First name:" + customer.getFirstname());
println("Last name:" + customer.getLastname());
println("Gender:" + customer.getGender());
println("PhoneNumber:" + customer.getPhoneNumber());
// Primary address
PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress();
println("PrimaryAddress:");
println("PostalCode:" + primaryAddress.getPostalCode());
println("AddressLine1:" + primaryAddress.getAddressLine1());
println("AddressLine2:" + primaryAddress.getAddressLine2());
// Billing address
BillingAddressType billingAddress = customer.getAddress().getBillingAddress();
println("BillingAddress:");
println("Receiver:" + billingAddress.getReceiver());
println("PostalCode:" + billingAddress.getPostalCode());
println("AddressLine1:" + billingAddress.getAddressLine1());
println("AddressLine2:" + billingAddress.getAddressLine2());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void println(String str) {
System.out.println(str);
}
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.customerReader();
}
}
q行?参看输出l果:
Customer#0
Customer ID:1
First name:Jessica
Last name:Lim
Gender:female
PhoneNumber:1234567
PrimaryAddress:
PostalCode:350106
AddressLine1:#25-1
AddressLine2:SHINSAYAMA 2-CHOME
BillingAddress:
Receiver:Ms Danielle
PostalCode:350107
AddressLine1:#167
AddressLine2:NORTH TOWER HARBOUR CITY
Customer#1
Customer ID:2
First name:David
Last name:Bill
Gender:male
PhoneNumber:808182
PrimaryAddress:
PostalCode:319087
AddressLine1:1033 WS St.
AddressLine2:Tima Road
BillingAddress:
Receiver:Mr William
PostalCode:672993
AddressLine1:1033 WS St.
AddressLine2:Tima Road
怎么?是不是很L? XMLBean的威?
六、利用XMLBean写XML文g
利用XMLBean创徏一个XML文档也是一件轻而易丄?我们再增加一个Method,
L(fng)一下的Java Class:
public void createCustomer() {
try {
// Create Document
CustomersDocument doc = CustomersDocument.Factory.newInstance();
// Add new customer
CustomerType customer = doc.addNewCustomers().addNewCustomer();
// set customer info
customer.setId(3);
customer.setFirstname("Jessica");
customer.setLastname("Lim");
customer.setGender("female");
customer.setPhoneNumber("1234567");
// Add new address
AddressType address = customer.addNewAddress();
// Add new PrimaryAddress
PrimaryAddressType primaryAddress = address.addNewPrimaryAddress();
primaryAddress.setPostalCode("350106");
primaryAddress.setAddressLine1("#25-1");
primaryAddress.setAddressLine2("SHINSAYAMA 2-CHOME");
// Add new BillingAddress
BillingAddressType billingAddress = address.addNewBillingAddress();
billingAddress.setReceiver("Ms Danielle");
billingAddress.setPostalCode("350107");
billingAddress.setAddressLine1("#167");
billingAddress.setAddressLine2("NORTH TOWER HARBOUR CITY");
File xmlFile = new File(filename);
doc.save(xmlFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
修改main method.
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.createCustomer();
}
q行,打开customers_new.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Customers>
<customer>
<id>3</id>
<gender>female</gender>
<firstname>Jessica</firstname>
<lastname>Lim</lastname>
<phoneNumber>1234567</phoneNumber>
<address>
<primaryAddress>
<postalCode>350106</postalCode>
<addressLine1>#25-1</addressLine1>
<addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
</primaryAddress>
<billingAddress>
<receiver>Ms Danielle</receiver>
<postalCode>350107</postalCode>
<addressLine1>#167</addressLine1>
<addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
</billingAddress>
</address>
</customer>
</Customers>
七、利用XMLBean修改XML文g
我们再增加一个Method:
public void updateCustomer(int id,String lastname) {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
if(customer.getId()==id){
customer.setLastname(lastname);
break;
}
}
doc.save(xmlFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
main method:
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.updateCustomer(3,"last");
}
q行之后,我们会(x)看到客户~号?的客L(fng)lastname已经改ؓ(f)last.
八、利用XMLBean删除一个customer
再增加一个Method:
public void deleteCustomer(int id) {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
if(customer.getId()==id){
customer.setNil() ;
break;
}
}
doc.save(xmlFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
main method:
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.deleteCustomer(3);
}
q行,我们会(x)看到客户~号?的客L(fng)资料已经被删?
?ji)、查询XML
除了(jin)本文在以上讲q的,利用XMLBean能轻L村֮成XML的读写操作外,l合XPath和XQuery,XMLBeanq能完成象SQL查询数据库一h便地查询XML数据. 关于XML查询以及(qing)如何创徏XML数据? 我将在另一文章里讨论.
十、结束语
XMLBean能帮助我们轻易读写XML,q将有助于我们降低XML的学?fn)和使?有了(jin)q个基础,开发h员将为学?fn)更多地XML相关技术和W(xu)eb Services,JMS{其他J2EE技术打下良好地基础.