1. java用XStream把xml轉換成javabean的問題
xStream可以輕易的將Java對象和xml文檔相互轉換,而且可以修改某個特定的屬性和節點名稱,而且也支持json的轉換;它們都完美支持JSON,但是對xml的支持還不是很好。一定程度上限制了對Java對象的描述,不能讓xml完全體現到對Java對象的描述。這里將會介紹xStream對JSON、XML的完美支持。xStream不僅對XML的轉換非常友好,而且提供annotation註解,可以在JavaBean中完成對xml節點、屬性的描述。以及對JSON也支持,只需要提供相關的JSONDriver就可以完成轉換。
2. jsp Form->Java Bean ->使用XStream->生成XML文件
[代碼]1.實體類:PersonBean
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("person")
public class PersonBean {
@XStreamAlias("firstName")
private String firstName;
@XStreamAlias("lastName")
private String lastName;
@XStreamAlias("telphone")
private PhoneNumber tel;
@XStreamAlias("faxphone")
private PhoneNumber fax;
//省略setter和getter }
main函數示例1:toxml
import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JsonWriter.Format; import com.thoughtworks.xstream.io.xml.DomDriver;
public class PersonTest {
public static void main(String[] args) {
PersonBean per=new PersonBean();
per.setFirstName("chen");
per.setLastName("youlong");
PhoneNumber tel=new PhoneNumber();
tel.setCode(137280);
tel.setNumber("137280968");
PhoneNumber fax=new PhoneNumber();
fax.setCode(20);
fax.setNumber("020221327");
per.setTel(tel);
per.setFax(fax);
//java對象轉換成xml
String xml=XmlUtil.toXml(per);
System.out.println("xml==="+xml);
}
}
main函數示例2:toBean
public static void main(String[] args) {
String xmlStr="<person>"+
"<firstName>chen</firstName>"+
"<lastName>youlong</lastName>"+
"<telphone>"+
"<code>137280</code>"+
"<number>137280968</number>"+
"</telphone>"+
"<faxphone>"+
"<code>20</code>"+
"<number>020221327</number>"+
"</faxphone>"+
"<friends>"+
"<name>A1</name>"+
"<name>A2</name>"+
"<name>A3</name>"+
"</friends>"+
"<pets>"+
"<pet>"+
"<name>doly</name>"+
"<age>2</age>"+
"</pet>"+
"<pet>"+
"<name>Ketty</name>"+
"<age>2</age>"+
"</pet>"+
"</pets>"+
"</person>"; //用泛型的知識
PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
System.out.println("person=firstname=="+person.getFirstName());
System.out.println("person==Friends==name1=="+person.getFriend().getName().get(0));
System.out.println("person==Pets==name2=="+person.getPet().getAnimalList().get(1).getName());
}
3. Java 中解析 XML 生成 Bean 實例,用什麼方式效率最高
用org.json以及谷歌提供gson來解析json數據的方式更好一些。
安卓下通常採用以下幾種方式解析json數據:
1、org.json包(已經集成到android.jar中了)
2、google提供的gson庫
3、阿里巴巴的fastjson庫
4、json-lib
以Google出品的Gson為例,具體步驟為:
1、首先,從 code.google.com/p/google-gson/downloads/list下載GsonAPI:
google-gson-1.7.1-release.zip 把gson-1.7.jar 到libs(項目根目錄新建一個libs文件夾)中。 可以使用以下兩種方法解析JSON數據,通過獲取JsonReader對象解析JSON數據。
代碼如下:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
JsonReader reader = new JsonReader(new StringReader(jsonData));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
String tagName = reader.nextName();
if(tagName.equals("username")){
System.out.println(reader.nextString());
}
else if(tagName.equals("userId")){
System.out.println(reader.nextString());
}
}
reader.endObject();
}
reader.endArray();
}
catch(Exception e){
e.printStackTrace();
}
2、使用Gson對象獲取User對象數據進行相應的操作:
代碼如下:
Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
3、如果要處理的JSON字元串只包含一個JSON對象,則可以直接使用fromJson獲取一個User對象:
代碼如下:
String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());
4. XML轉換成JavaBean
用Dom4j和SAX解析配置文件成java Bean對象
分類: java 2011-08-05 11:13 138人閱讀 評論(0) 收藏 舉報
[java] view plain
用Dom4j和SAX兩種方式將如下配置文件解析成java Bean對象。配置文件(config.xml)如下:<pre class="html" name="code"><?xml version="1.0" encoding="UTF-8"?>
<Beans>
<Bean className="Test" classComment="測試類">
<Field name="name" type="String" comment="名字" />
<Field name="sex" type="Integer" comment="性別" />
</Bean>
<Bean className="Test1" classComment="測試類1">
<Field name="name1" type="String" comment="名字1" />
<Field name="sex1" type="Integer" comment="性別1" />
</Bean>
</Beans>
[java] view plain
首先定義java的三個類Beans、Bean、Field 來承載配置文件的節點,類定義如下:
[java] view plain
/**
* 總對象
* @author
*/
public class Beans {
private ArrayList<Bean> listBean = new ArrayList<Bean>();;
public ArrayList<Bean> getListBean() {
return listBean;
}
public void setListBean(ArrayList<Bean> listBean) {
this.listBean = listBean;
}
}
/**
* 一個Class Bean
* @author
*
*/
public class Bean {
private String className;//類名
private String classComment;//類注釋
private ArrayList<Field> listField = new ArrayList<Field>();
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getClassComment() {
return classComment;
}
public void setClassComment(String classComment) {
this.classComment = classComment;
}
public ArrayList<Field> getListField() {
return listField;
}
public void setListField(ArrayList<Field> listField) {
this.listField = listField;
}
}
/**
* Bean 中的屬性對象
* @author
*
*/
public class Field {
//類型
private String type;
//欄位名字
private String name;
//欄位注釋
private String comment;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
第一種方式:通過Dom4j的方式解析xml文件:
[java] view plain
[java] view plain
/**
* 將xml格式的字元串轉成Beans對象
* @param xml
* @return
*/
public static Beans parseXml(String xml)
{
Beans returnObj = new Beans();
Document doc = null;
try{
// doc = DocumentHelper.parseText(xml); 原版轉的是用的這種方式獲取document對象,但是測試出錯。自己換成了下面方式獲取document對象就對了。
SAXReader reader = new SAXReader();
doc = reader.read(new File(xml));
Element root = doc.getRootElement();
//obj list
List list_el = root.elements();
if(list_el !=null && list_el.size()>0)
{
for(int i =0;i<list_el.size();i++)
{
Element obj_el = (Element) list_el.get(i);
//解析obj 節點
Bean obj = parseObj(obj_el);
returnObj.getListBean().add(obj);
}
}
}catch(Exception e){
e.printStackTrace();
}
return returnObj;
}
/**
* 解析Bean節點
* @param obj_el
* @return
*/
private static Bean parseObj(Element obj_el)
{
Bean obj = new Bean();
obj.setClassName(obj_el.attributeValue("className"));
obj.setClassComment(obj_el.attributeValue("classComment"));
//獲取field 列表
List list_field = obj_el.elements();
if(list_field != null && list_field.size() > 0)
{
for(int i = 0;i<list_field.size();i++)
{
Element field_el = (Element)list_field.get(i);
//解析field節點
Field field = parseField(field_el);
obj.getListField().add(field);
}
}
return obj;
}
/**
* 解析Field屬性
* @param field_el
* @return
*/
private static Field parseField(Element field_el)
{
Field field = new Field();
List list_attr = field_el.attributes();
if(list_attr != null && list_attr.size() > 0)
{
for(int i=0;i<list_attr.size();i++)
{
Attribute field_attr = (Attribute)list_attr.get(i);
String key = field_attr.getName();
String value = field_attr.getText();
if(key.equals("name"))
{
field.setName(value);
}
else if(key.equals("type"))
{
field.setType(value);
}
else if(key.equals("comment"))
{
field.setComment(value);
}
}
}
return field;
}
5. 怎麼用jaxb技術將xml轉成javabean
Java代碼
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement(name="mole")
public class Mole extends Metadata{
@XmlAttribute(name="name")
public String name;
@XmlAttribute(name="template")
public String template;
@XmlElement
public Resources resources;
@XmlElement
public HeaderItems headerItems;
@XmlElement
public Properties properties;
@XmlElement
public BodyItems bodyItems;
@XmlTransient
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlTransient
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
@XmlTransient
public Resources getResources() {
return resources;
}
public void setResources(Resources resources) {
this.resources = resources;
}
@XmlTransient
public HeaderItems getHeaderItems() {
return headerItems;
}
public void setHeaderItems(HeaderItems headerItems) {
this.headerItems = headerItems;
}
@XmlTransient
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@XmlTransient
public BodyItems getBodyItems() {
return bodyItems;
}
public void setBodyItems(BodyItems bodyItems) {
this.bodyItems = bodyItems;
}
}
Moel對象其中一個對象屬性:
Java代碼
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class HeaderItems extends Metadata {
@XmlElement(name="field")
private List<Field> fields;
@XmlTransient
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
for (int i=0; i<fields.size(); i++)
fields.get(i).setHeaderItem(true);
}
public void clear() {
fields.clear();
}
}
Java代碼
package com.morningstar.wfe.metadata.node;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class Map extends Datasource {
@XmlAttribute(name="name")
public String name;
@XmlAttribute(name="type")
public String type;
@XmlAttribute(name="url")
public String url;
@XmlElement
public Entries entries;
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public void setEntries(Entries entries) {
this.entries = entries;
}
@XmlTransient
public String getName() {
return name;
}
@XmlTransient
public String getType() {
return type;
}
@XmlTransient
public Entries getEntries() {
return this.entries;
}
@XmlTransient
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int size() {
if (entries == null) return 0;
return entries.size();
}
public Entry get(int index) {
if (entries == null) return null;
return entries.get(index);
}
public List<Entry> getEntriesList() {
return entries.getEntryList();
}
}
最後XML閃亮登場:
Java代碼
<?xml version="1.0" encoding="UTF-8"?>
<mole name='showcase' template='showcase.ftl'>
<resources>
<map name='css' type='static'>
<entries>
<entry label="text_a1" value="text_a1"></entry>
<entry label="text_a2" value="text_a2"></entry>
<entry label="text_a3" value="text_a3"></entry>
<entry label="text_c1" value="text_c1"></entry>
<entry label="text_c2" value="text_c2"></entry>
</entries>
</map>
<map name='status' type='ws' url="xxxx">
</map>
<map name='author' type='file' url="xxxx">
</map>
</resources>
<headerItems>
<field name='active1' type='checkbox' datasource='css'
multiple='false' />
<field name='title1' type='text' format="string" required="true"/>
<field name='radio11' type='radio' datasource='css'/>
<field name='url11' type='url' format="string"/>
<field name='dropdownlist111' type='select' datasource='css' multiple="true" height="80" width="100"/>
<field name='title22' type='textarea' width="200" height="100" spellCheck="true" format="string" required="true"/>
</headerItems>
<properties>
<field name='active12' type='checkbox' datasource='status'
multiple='false' />
<field name='title12' type='date' format="int" />
<field name='email11' type='email' visible="true" />
</properties>
<bodyItems>
<field label="Name" name="name" type="text" visible="false"
editable="false"></field>
<field name="readings_list" type="datatable" action="insert,remove">
<columns>
<field label="Title" name="rSource" type="text" visible="true" width="30"/>
<field label="URL" name="rURL" type="text" visible="true" width="40"/>
<field label="Date" name="rDate" type="text" visible="true" width="50"/>
<field label="Source" name="rSource" type="text" visible="true" width="60"/>
</columns>
</field>
</bodyItems>
</mole>
Metadata是一個抽象類,描述了些 ID NAME VALUE基本屬性 沒什麼特別的
關於XML轉java對象的操作:
Java代碼
public static Mole parse(String metadata) throws MetadataParserException {
Mole mole = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Mole.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
mole = (Mole)um.unmarshal(new ByteArrayInputStream(metadata.getBytes()));
} catch (JAXBException e) {
log.warn("JAXB castor failed to convert the metadata to mole instance by {}",e.getMessage());
throw new MetadataParserException();
}
return mole;
}
這樣的話傳進XML的字元串,就可以解析出這個JAVA對象。完全不用寫任何過多的代碼。豈不爽哉?!!!!
附一個java bean <=> xml 的unmi同志原創文檔,主要是比較Jaxb和castor。
6. 如何用java生成一個xml文件
//首先下載並添加dom4j.jar包(自己下載)
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @author wsj
*/
public class Test1 {
public static void main(String[] args) throws Exception {
Document dom=DocumentHelper.createDocument();//創建文件
Element root=dom.addElement("XVal");//添加根元素,Xval
root.addAttribute("X", "X字元串的值");
root.setText("Xval標簽中間的值");
String xml=dom.asXML();
System.out.println(xml);
File f=new File("d:/xml.xml");
PrintWriter pw=new PrintWriter(f);
pw.write(xml);
pw.close();
JOptionPane.showMessageDialog(null, "已生成xml文件,路徑為為d:/xml.xml");
}
}
7. 如何根據xml和schema文件生成java類(用程序實現)!
JAXB提供了可以從schema生成java類,下面簡要介紹一下生成的步驟:
1:下載jaxb包 jaxb 2_1_9.zip ,在本博客中可以下載得到。解壓後得到四個目錄,包含bin、lib 、docs、example
2:在"cmd"里進入到bin目錄,如C:/>cd C:/jaxb2.1.9/bin 回車
3:輸入xjc c:/students.xsd -d c:/src -p com.entity 回車
註:-d 說明要生成的java類存放目錄
-p 為生成java類指定的包名
students.xsd 為自己定義的Schema
8. javabean欄位如何生成特殊形式的xml 值
//1.需要 用dom4j jar包 (maven依賴
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.0</version>
</dependency>)
//2.輸出javabean的xml格式字元串
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class JavaBeanXml {
private String id;
private String name;
private Integer age;
public JavaBeanXml(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
//輸出javabean的xml格式字元串
public String getXMLString(){
Document d=DocumentHelper.createDocument();
Element root=d.addElement(this.getClass().getSimpleName());
root.addElement("id").addText(getId());
root.addElement("name").addText(getName());
root.addElement("age").addText(String.valueOf(getAge()));
d.setXMLEncoding("utf-8");
return d.asXML();
}
}
//3.測試類
public class JavaBeanXmlTest {
public static void main(String[] args) {
JavaBeanXml jxml=new JavaBeanXml("1","張三",23);
System.out.println(jxml.getXMLString());
}
}