
正文
xml转换成java代码,java将xml格式字符串转换成
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
100分求高手帮我将xml文件转为java类
奋斗了20个小时,终于完成了,本类无需导入任何额外的包,底层细节全部在本类中完成!
说明,本类通过读入xml文件,并把信息正确分成存入到Guird列表中。通过调用getGuirdList()将返回结果集。要使用其中的某一项,只接到对象中用方法获取即可,希望能够满足楼主的需求!!
TransXml.java
import java.io.*;
import java.util.Vector;
import java.util.Scanner;
import java.io.InputStreamReader;
import java.util.LinkedList;
public class TransXml{
private String xmlAddress;
private VectorGuird guir;//表示一级子目录下的Guird向量
private FileInputStream inStr;
private InputStreamReader inRea;
private int whLayer=0;//标志表的层次,为0表示根表,为1表示第一层子表
private int whiLab=0;//表示当前标签是第几层
boolean isend=false;
boolean isguirs=false;
boolean isguir=false;
StringBuffer str=new StringBuffer();//表示中的词
String strVul;
StringBuffer value=new StringBuffer();//表示具体类容
boolean isWorld=false;
boolean isValue=false;
boolean isSubgu=false;
boolean notEnd=true;
LinkedListGuird linList;
public TransXml(){
}
public TransXml(String xmlAdd){
guir=new VectorGuird();
linList=new LinkedListGuird();
this.xmlAddress=xmlAdd;
System.out.println("开始读取xml文件");
try{
inStr=new FileInputStream(xmlAddress);
inRea=new InputStreamReader(inStr);
}catch(IOException e){
System.out.println("Xml文件地址无效");
}
System.out.println("开始读取xml文件完成!");
Translate();
}
public void Translate(){
Guird theGu=new Guird();
while(notEnd)
{
int tt=-1;
try{
tt=inRea.read();
}catch(IOException e){
System.out.println("字符读取失败!");
}
if(tt==-1){//文件已经读完了
notEnd=false;
break;
}
char ch=(char)tt;
if(ch==''){
//说明,前面如果有类容的话,内容完结
isValue=false;//说明内容已经完了
isWorld=true;//表示下面是里德内容
}
if(ch==''){
isWorld=false;//表示括号内的字符串结束了
strVul=str.toString();//表示当前的目录层次
if(strVul.equalsIgnoreCase("guirds")){//这是配置文件正式开始的标志
isguirs=true;
}else if(strVul.equalsIgnoreCase("guird")){//说明已经进入guird类
isguir=true;
}else if(strVul.equalsIgnoreCase("id")){//进入id属性
isValue=true;
}else if(strVul.equalsIgnoreCase("name")){//进入name属性
isValue=true;
}else if(strVul.equalsIgnoreCase("ename")){//进入ename属性
isValue=true;
}else if(strVul.equalsIgnoreCase("parentid")){//进入parentid属性
isValue=true;
}else if(strVul.equalsIgnoreCase("subguirds")){//进入subguirds属性,说明它还有一个字表
isSubgu=true;
linList.addLast(theGu);//做入栈操作,添加到结尾
whLayer++;//原始的值为0,它表示当前操作guird的级数
//那么下面的读取将是新的Guird类,所以要把现在的theGu保存后重新初始化
theGu=new Guird();//初始化,后面接着用
}else if(strVul.equalsIgnoreCase("/guirds")){//这是配置文件结束的标志
isguirs=false;//程序已经阅读完毕XML文件
notEnd=false;
}else if(strVul.equalsIgnoreCase("/guird")){//说明已经结束guird类
isguir=false;//说明一条记录已经完成,所以要对其存储
//theGu的属性是在/标签前就写入完毕了,那么应该写入上级目录中,
//如果是定定及目录,则直接写入给定的Vector
if(whLayer0){//说明还不是根目录
Guird tempguir=linList.getLast();
VectorGuird tempqq=(Vector)tempguir.getSubGuird();
if(tempqq==null){//说明前面的集合为空
tempqq=new Vector();
}
tempqq.add(theGu);//集合中增加这一项
tempguir.setSubGuird(tempqq);
linList.removeLast();//移动原来的换新的内容
linList.add(tempguir);
theGu=new Guird();//重新初始化供后面使用,并不要去改变whLayer值
}else if(whLayer==0){//这说明当前的theGu是指1级子目录,
guir.add(theGu);//添加一条记录到Vector
theGu=new Guird();// 重新初始化以便下次正确用到
}else{
System.out.println("xml文件标签错误!");
notEnd=false;
}
}else if(strVul.equalsIgnoreCase("/id")){//结束id属性
isValue=false;
theGu.setId(new Integer(value.toString()));
value=new StringBuffer();
}else if(strVul.equalsIgnoreCase("/name")){//结束name属性
isValue=false;
theGu.setName(value.toString());
// System.out.println("这里写入的名字是:"+theGu.getName());
value=new StringBuffer();
}else if(strVul.equalsIgnoreCase("/ename")){//结束ename属性
isValue=false;
theGu.setEname(value.toString());
value=new StringBuffer();
}else if(strVul.equalsIgnoreCase("/parentid")){//结束parentid属性
isValue=false;
theGu.setParentId(new Integer(value.toString()));
value=new StringBuffer();
}else if(strVul.equalsIgnoreCase("/subguirds")){//结束subguirds属性,字表完成
isSubgu=false;
//刚刚结束的这个Guird就是whLayer级子目录
//要判断是根类还是那一级子目录
whLayer--;//表示上一级目录
if(whLayer0){
theGu=linList.getLast();//成为当前节点
//所以当前操作对象又将是刚从LinkedListed中取出的那个
linList.removeLast();//已经用过了,最后一个移除,相当于退栈
}
else if(whLayer==0){//根节点下
theGu=linList.getLast();
linList.removeLast();
}else{
notEnd=false;//因为whLayer不可能小于0
System.out.println(xmlAddress+"标签不完整!请检查!");
break;
}
}
strVul="";
str=new StringBuffer();//重新初始化,准备后面使用
}
if(isWorld==true){
if((char)tt!=''(char)tt!='')//因为具有延时性所以要增加这个条件
if(tt!=32tt!=9)//它不为空格和Tab,即在xml中标签内的内容将忽略Tab和空格
str.append((char)tt);
}
if(isValue==true){//当前是类容属性值
if((char)tt!=''(char)tt!=''){
if(tt!=32tt!=9)//它不为空格和Tab
value.append((char)tt);
}
}
/**
* 为什么这里注释掉了,因为前面以当发现value值取到最后一位后就设置isValue为false
* 但是要当下一个/结尾标签完才会调用value值并进行操作,所以,value不能立刻变为空内容
* 那么当它被使用后,采设置新的对象是可取的
* else{
* value=new StringBuffer();//避免干扰下次
* }
*/
}
try{
inRea.close();
inStr.close();
}catch(IOException e){
System.out.println("流关闭失败!");
}
}
public Vector getGuirdList(){
return this.guir;//获得最终的子目录列表
}
/**
* 原来写的main方法进行测试,在这里就省略了
*/
}
Xml文件中guirds标签中,有几对guird标签就会返回几条结果,当然guird是指在guirds目录下的第一层标签,而其他的二级guird标签中的内容则存在相应的ListGuird subGuird中。
That's all !
相关问答
Q1: 如何将xml文件转变成java对象
首先 java是面向对象的编程语言,所以你要理解面向对象的思想。在这个前提下我们可以理解 文件 本身就是java的对象File,而xml只是File类中对象的一种实例。你可以创建一个File 把你的xml的路径传入这个对象的有参构造,这样就实例化了一个xml文件类的对象
Q2: 请问这句xml代码如何转换java代码
这个属性是隐藏的,没有对应的java接口
public static void setCursorDrawableColor(EditText editText, int color) {
try {
Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
fCursorDrawableRes.setAccessible(true);
int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);
Field fEditor = TextView.class.getDeclaredField("mEditor");
fEditor.setAccessible(true);
Object editor = fEditor.get(editText);
Class? clazz = editor.getClass();
Field fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
fCursorDrawable.setAccessible(true);
Drawable[] drawables = new Drawable[2];
drawables[0] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
drawables[1] = editText.getContext().getResources().getDrawable(mCursorDrawableRes);
drawables[0].setColorFilter(color, PorterDuff.Mode.SRC_IN);
drawables[1].setColorFilter(color, PorterDuff.Mode.SRC_IN);
fCursorDrawable.set(editor, drawables);
} catch (Throwable ignored) {
}
}
你试试这个方法,在stackoverflow上搜出来的
Q3: 如何创建xstream的注解工厂类,将xml转换成java对象
本文记录一下使用xstream这个api的注解特性对Java对象与XML字符串相互转换的一些代码示例。
我们很多人都处理过XML文件,也有很多非常成熟的第三方开源软件。如:jdom、dom4j等。虽然他们的功能非常强大,但在使用上还是有点不那么习惯。对于格式比较固定的XML文档,它的结构没有变化或是很少变化,这时将它转换成我们熟悉的Java对象来操作的话,会使工作变得更容易一些,而xstream正好可以满足这一点。
本文所用xstream的版本为:1.4.7
dependency
groupIdcom.thoughtworks.xstream/groupId
artifactIdxstream/artifactId
version1.4.7/version
/dependency
还是以之前的book XML为例,先上代码。
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("book")
public class Book {
// 别名注解,这个别名就是XML文档中的元素名,Java的属性名不一定要与别名一致
@XStreamAlias("name")
private String name;
@XStreamAlias("author")
private String author;
// 属性注解,此price就是book的属性,在XML中显示为:book price="108"
@XStreamAsAttribute()
@XStreamAlias("price")
private String price;
省略get和set方法
}
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("books")
public class Books {
// 隐式集合,加上这个注解可以去掉book集合最外面的list/list这样的标记
@XStreamImplicit
private ListBook list;
省略get和set方法
}
Q4: 如何根据xml和schema文件生成java类(用程序实现)!
验证应该好写吧,主要是解析xml
可以使用工具包dom4j
类似例子
dom4j参见
public static void readXML() throws DocumentException {
SAXReader sr = new SAXReader();// 获取读取xml的对象。
Document doc = sr.read("src/com/pzr/test/zhidao/test.xml");// 得到xml所在位置。然后开始读取。并将数据放入doc中
Element el_root = doc.getRootElement();// 向外取数据,获取xml的根节点。
Iterator it = el_root.elementIterator();// 从根节点下依次遍历,获取根节点下所有子节点
while (it.hasNext()) {// 遍历该子节点
Object o = it.next();// 再获取该子节点下的子节点
Element el_row = (Element) o;
String s = el_row.getText();
Iterator it_row = el_row.elementIterator();
while (it_row.hasNext()) {// 遍历节点
Element el_ename = (Element) it_row.next();// 获取该节点下的所有数据。
System.out.println(el_ename.getText());
}
}
}
Q5: 怎么用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="module")
public class Module 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;
}
}
Moduel对象其中一个对象属性:
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 ListField fields;
@XmlTransient
public ListField getFields() {
return fields;
}
public void setFields(ListField fields) {
this.fields = fields;
for (int i=0; ifields.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 ListEntry getEntriesList() {
return entries.getEntryList();
}
}
最后XML闪亮登场:
Java代码
?xml version="1.0" encoding="UTF-8"?
module 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
/module
Metadata是一个抽象类,描述了些 ID NAME VALUE基本属性 没什么特别的
关于XML转java对象的操作:
Java代码
public static Module parse(String metadata) throws MetadataParserException {
Module module = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Module.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
module = (Module)um.unmarshal(new ByteArrayInputStream(metadata.getBytes()));
} catch (JAXBException e) {
log.warn("JAXB castor failed to convert the metadata to module instance by {}",e.getMessage());
throw new MetadataParserException();
}
return module;
}
这样的话传进XML的字符串,就可以解析出这个JAVA对象。完全不用写任何过多的代码。岂不爽哉?!!!!
附一个java bean = xml 的unmi同志原创文档,主要是比较Jaxb和castor。







