JXPath 除了可以 XPath 语法访问 JavaBeans、DOM/JDOM,也可以对其属性赋值。

以下面的 JavaBeans 为例。

package com.huey.jxpath;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; @Data
@NoArgsConstructor
@AllArgsConstructor
public class Book { private String title;
private Author[] authors;
private Publisher publisher;
private String isbn;
private double price; }

Book.java

package com.huey.jxpath;

import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; @Data
@NoArgsConstructor
@AllArgsConstructor
public class Author { private String firstName;
private String lastName;
private char gender;
private Date birthday; }

Author.java

package com.huey.jxpath;

import java.util.Map;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; @Data
@NoArgsConstructor
@AllArgsConstructor
public class Publisher { private String name;
private String address;
private Map<String, String> contacts; }

Publisher.java

初始化:

Author[] authors;
Publisher publisher;
Book book; authors = new Author[] {
new Author("Eric", "Freeman", 'F', new Date()),
new Author("ElElisabeth", "Freeman", 'M', new Date())
}; Map<String, String> contacts = new HashMap<String, String>();
contacts.put("tel", "010-12345678");
contacts.put("fax", "010-87654321");
contacts.put("email", "test@163.com");
publisher = new Publisher("中国电力出版社", "北京市XX区YY路Z号", contacts); book = new Book("Head First Design Patterns", authors, publisher, "9787508353937", 98.0);

Setting Properties

JXPathContext context = JXPathContext.newContext(book);
context.setValue("publisher/name", "人民邮电出版社");
context.setValue("publisher/contacts/attribute::email", "test@gmail.com");

Creating Objects

当对 JavaBean 的复杂数据类型属性设置值时,如果属性没有实例化,则会抛出一个 JXPathException 异常。实现 AbstractFactory 接口后,再调用 context.createPath 方法,能够在复杂数据类型对象为 null 时,为其实例化。context.createPathAndSetValue 方法能够在实例化对象的同时设置值。

package com.huey.jxpath;

import java.lang.reflect.Array;
import java.util.HashMap; import org.apache.commons.jxpath.AbstractFactory;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.Pointer; public class BookFactory extends AbstractFactory { @Override
public boolean createObject(JXPathContext context, Pointer pointer,
Object parent, String name, int index) { if (parent instanceof Book && "authors".equals(name)) {
Book book = (Book) parent;
if (book.getAuthors() == null) {
book.setAuthors(new Author[]{});
}
int newSize = index + 1;
int oldSize = book.getAuthors().length;
if (newSize > oldSize) {
Author[] newAuthors = (Author[]) resizeArray(book.getAuthors(), newSize);
book.setAuthors(newAuthors);
}
return true;
}
if (parent instanceof Book && "publisher".equals(name)) {
((Book)parent).setPublisher(new Publisher());
return true;
}
if (parent instanceof Publisher && "contacts".equals(name)) {
((Publisher)parent).setContacts(new HashMap<String, String>());
return true;
}
return false;
} /**
* 调整数组长度,当新的数组长度大于旧的数组长度时,实例化所有新增的元素
* @param oldArray
* @param newSize
* @return
*/
private Object resizeArray (Object oldArray, int newSize) {
int oldSize = Array.getLength(oldArray);
Class<?> elementType = oldArray.getClass().getComponentType(); Object newArray = Array.newInstance(elementType, newSize);
int preserveLength = Math.min(oldSize, newSize);
if (preserveLength > 0) {
System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
}
try {
for (int i = preserveLength; i < newSize; i++) {
Array.set(newArray, i, elementType.newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
return newArray;
} }
JXPathContext context = JXPathContext.newContext(new Book());
context.setFactory(new BookFactory());
context.createPathAndSetValue("title", "hello jxpath");
context.createPathAndSetValue("authors[1]/gender", 'F');
// Map 对象的 xpath 必须使用 contacts/email 或 contacts/child::email 而不能使用 contacts[@email] 或 contacts/attribute::email
context.createPathAndSetValue("publisher/contacts/child::email", "test@gmial.com");

Commons JXPath - Modifying Object Graphs的更多相关文章

  1. Python Object Graphs — objgraph 1.7.2 documentation

    Python Object Graphs - objgraph 1.7.2 documentation Python Object Graphs¶ objgraph is a module that ...

  2. Commons JXPath - Object Graph Traversal

    JXPath 提供了使用 Xpath 语法操纵符合 Java 类命名规范的 JavaBeans 的工具.也支持 maps.DOM 和其他对象模型.对于深层次结构的 JavaBean,使用 JXPath ...

  3. Commons JXPath - DOM/JDOM Document Access

    除了 JavaBean,JXPath 也可以访问 DOM/JDOM. 示例 XML: <?xml version="1.0" encoding="utf-8&quo ...

  4. Commons JXPath - Extension Functions

    Standard Extension Functions 创建新的对象 JXPathContext context = JXPathContext.newContext(null); Book boo ...

  5. Table of Contents - Apache Commons

    Apache Commons 简述 CLI Usage of CLI Option Properties Codec 常见的编码解码 Compress Configuration2 Quick sta ...

  6. 编写更少量的代码:使用apache commons工具类库

    Commons-configuration   Commons-FileUpload   Commons DbUtils   Commons BeanUtils  Commons CLI  Commo ...

  7. Apache Commons 工具集

    一.Commons BeanUtils http://jakarta.apache.org/commons/beanutils/index.html 说明:针对Bean的一个工具集.由于Bean往往是 ...

  8. apache commons Java包简介

    更多信息,请参考:http://commons.apache.org/ 一.Commons BeanUtils说明:针对Bean的一个工具集.由于Bean往往是有一堆get和set组成,所以BeanU ...

  9. Apache Commons 工具集使用简介

    Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.我选了一些比较常用的项目做简单介绍.文中用了很多网上现成的东西,我只是做了一个汇总整理. 一.Comm ...

随机推荐

  1. Chrome的Postman的使用

    Chrome提供了一个很好的Web App 名为 Postman 使用这个web app,你可以输入一个url,然后可以很清楚的看到返回的各种结果 直接在Google中输入Postman, 找到它   ...

  2. C#学习笔记(八):扩展方法

    还记得第一次使用DOTween时,发现缓动方法竟然是可以直接用Transform对象中调用到,当时就被震撼到了(那是还是C#小白一只).好了不多说了,今天来学习一下C#的这个特性——扩展方法. 扩展方 ...

  3. 修改mysql字符编码出现Job failed to start解决办法

        从网上找到如下资料: $sudo gedit /etc/mysql/my.cnf [client]下添加: default-character-set=utf8 [mysqld]下添加: de ...

  4. 三、FreeMarker 模版开发指南 第三章 模版

    章节内容如下:   总体结构 指令 表达式 插值 一.总体结构 实际上你用程序语言编写的程序就是模板,模板也被称为FTL(代表FreeMarker模板语言).这是为编写模板设计的非常简单的编程语言. ...

  5. 预览Cube出现没有注册类错误

    用Microsoft SQL Server Management Studio预览AS上的Cube 出现如下错误. TITLE: Microsoft SQL Server Management Stu ...

  6. delphi array应用 DayOfWeek星期几判断

    //array应用 DayOfWeek星期几判断 procedure TForm1.Button1Click(Sender: TObject);var    days:array[1..7] of s ...

  7. Ruby on Rails Tutorial 第五章 完善布局

    本章目标:局部视图.Rails路由.Asset Pipeline.Sass1.Bootstrap是Twitter开发的开源Web设计框架mockup是网页构思图,在web领域经常称之为“线框图”,用于 ...

  8. 10+ commonly using find command switches with example Unix/Linux

    http://crybit.com/find-command-usage-with-example-unixlinux/ find command is one of the best search ...

  9. Linux shell 脚本攻略之正则表达式入门

    摘自:<Linux shell 脚本攻略> 下面是类似的解释:

  10. 2014年GCT考试报名时

    第一阶段: 网上报名时间预计为2014年6月20日至2014年7月10日. 考生可在6月20日后在中国学位与研究生教育信息网(http://www.chinadegrees.cn/)网站报名.网报时按 ...