精华内容
下载资源
问答
  • import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.sql.Connection;import java.s...

    package com.song;

    import java.io.BufferedWriter;

    import java.io.File;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.OutputStreamWriter;

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map;

    /**

    *  自动生成MyBatis的实体类、实体映射XML文件、Mapper

    *

    * @author   WYS

    * @date     2014-11-8

    * @version  v1.0

    */

    @SuppressWarnings("hiding")

    public class EntityUtil {

    /**

    **********************************使用前必读*******************

    **

    ** 使用前请将moduleName更改为自己模块的名称即可(一般情况下与数据库名一致),其他无须改动。

    **

    ***********************************************************

    */

    private final String type_char ="char";

    private final String type_date ="date";

    private final String type_timestamp ="timestamp";

    private final String type_int ="int";

    private final String type_bigint ="bigint";

    private final String type_text ="text";

    private final String type_bit ="bit";

    private final String type_decimal ="decimal";

    private final String type_blob ="blob";

    private final String moduleName ="group";// 对应模块名称(根据自己模块做相应调整!!!务必修改^_^)

    private final String bean_path ="d:/entity_bean";

    private final String mapper_path ="d:/entity_mapper";

    private final String xml_path ="d:/entity_mapper/xml";

    private final String bean_package ="net.yunxiaoyuan." + moduleName +".entity";

    private final String mapper_package ="net.yunxiaoyuan." + moduleName +".mapper";

    private final String driverName ="com.mysql.jdbc.Driver";

    private final String user ="test";

    private final String password ="test";

    private final String url ="jdbc:mysql://192.168.1.253:3306/" + moduleName +"?characterEncoding=utf8";

    private String tableName =null;

    private String beanName =null;

    private String mapperName =null;

    private Connection conn =null;

    private void init()throws ClassNotFoundException, SQLException {

    Class.forName(driverName);

    conn = DriverManager.getConnection(url, user, password);

    }

    /**

    *  获取所有的表

    *

    * @return

    * @throws SQLException

    */

    private List getTables()throws SQLException {

    List tables =new ArrayList();

    PreparedStatement pstate = conn.prepareStatement("show tables");

    ResultSet results = pstate.executeQuery();

    while ( results.next() ) {

    String tableName = results.getString(1);

    //          if ( tableName.toLowerCase().startsWith("yy_") ) {

    tables.add(tableName);

    //          }

    }

    return tables;

    }

    private void processTable( String table ) {

    StringBuffer sb =new StringBuffer(table.length());

    String tableNew = table.toLowerCase();

    String[] tables = tableNew.split("_");

    String temp =null;

    for (int i =1 ; i < tables.length ; i++ ) {

    temp = tables[i].trim();

    sb.append(temp.substring(0,1).toUpperCase()).append(temp.substring(1));

    }

    beanName = sb.toString();

    mapperName = beanName +"Mapper";

    }

    private String processType( String type ) {

    if ( type.indexOf(type_char) > -1 ) {

    return "String";

    }else if ( type.indexOf(type_bigint) > -1 ) {

    return "Long";

    }else if ( type.indexOf(type_int) > -1 ) {

    return "Integer";

    }else if ( type.indexOf(type_date) > -1 ) {

    return "java.util.Date";

    }else if ( type.indexOf(type_text) > -1 ) {

    return "String";

    }else if ( type.indexOf(type_timestamp) > -1 ) {

    return "java.util.Date";

    }else if ( type.indexOf(type_bit) > -1 ) {

    return "Boolean";

    }else if ( type.indexOf(type_decimal) > -1 ) {

    return "java.math.BigDecimal";

    }else if ( type.indexOf(type_blob) > -1 ) {

    return "byte[]";

    }

    return null;

    }

    private String processField( String field ) {

    StringBuffer sb =new StringBuffer(field.length());

    //field = field.toLowerCase();

    String[] fields = field.split("_");

    String temp =null;

    sb.append(fields[0]);

    for (int i =1 ; i < fields.length ; i++ ) {

    temp = fields[i].trim();

    sb.append(temp.substring(0,1).toUpperCase()).append(temp.substring(1));

    }

    return sb.toString();

    }

    /**

    *  将实体类名首字母改为小写

    *

    * @param beanName

    * @return

    */

    private String processResultMapId( String beanName ) {

    return beanName.substring(0,1).toLowerCase() + beanName.substring(1);

    }

    /**

    *  构建类上面的注释

    *

    * @param bw

    * @param text

    * @return

    * @throws IOException

    */

    private BufferedWriter buildClassComment( BufferedWriter bw, String text )throws IOException {

    bw.newLine();

    bw.newLine();

    bw.write("/**");

    bw.newLine();

    bw.write(" * ");

    bw.newLine();

    bw.write(" * " + text);

    bw.newLine();

    bw.write(" * ");

    bw.newLine();

    bw.write(" **/");

    return bw;

    }

    /**

    *  构建方法上面的注释

    *

    * @param bw

    * @param text

    * @return

    * @throws IOException

    */

    private BufferedWriter buildMethodComment( BufferedWriter bw, String text )throws IOException {

    bw.newLine();

    bw.write("\t/**");

    bw.newLine();

    bw.write("\t * ");

    bw.newLine();

    bw.write("\t * " + text);

    bw.newLine();

    bw.write("\t * ");

    bw.newLine();

    bw.write("\t **/");

    return bw;

    }

    /**

    *  生成实体类

    *

    * @param columns

    * @param types

    * @param comments

    * @throws IOException

    */

    private void buildEntityBean( List columns, List types, List comments, String tableComment )

    throws IOException {

    File folder =new File(bean_path);

    if ( !folder.exists() ) {

    folder.mkdir();

    }

    File beanFile =new File(bean_path, beanName +".java");

    BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(beanFile)));

    bw.write("package " + bean_package +";");

    bw.newLine();

    bw.write("import java.io.Serializable;");

    bw.newLine();

    //bw.write("import lombok.Data;");

    //      bw.write("import javax.persistence.Entity;");

    bw = buildClassComment(bw, tableComment);

    bw.newLine();

    bw.write("@SuppressWarnings(\"serial\")");

    bw.newLine();

    //      bw.write("@Entity");

    //bw.write("@Data");

    //bw.newLine();

    bw.write("public class " + beanName +" implements Serializable {");

    bw.newLine();

    bw.newLine();

    int size = columns.size();

    for (int i =0 ; i < size ; i++ ) {

    bw.write("\t/**" + comments.get(i) +"**/");

    bw.newLine();

    bw.write("\tprivate " + processType(types.get(i)) +" " + processField(columns.get(i)) +";");

    bw.newLine();

    bw.newLine();

    }

    bw.newLine();

    // 生成get 和 set方法

    String tempField =null;

    String _tempField =null;

    String tempType =null;

    for (int i =0 ; i < size ; i++ ) {

    tempType = processType(types.get(i));

    _tempField = processField(columns.get(i));

    tempField = _tempField.substring(0,1).toUpperCase() + _tempField.substring(1);

    bw.newLine();

    //          bw.write("\tpublic void set" + tempField + "(" + tempType + " _" + _tempField + "){");

    bw.write("\tpublic void set" + tempField +"(" + tempType +" " + _tempField +"){");

    bw.newLine();

    //          bw.write("\t\tthis." + _tempField + "=_" + _tempField + ";");

    bw.write("\t\tthis." + _tempField +" = " + _tempField +";");

    bw.newLine();

    bw.write("\t}");

    bw.newLine();

    bw.newLine();

    bw.write("\tpublic " + tempType +" get" + tempField +"(){");

    bw.newLine();

    bw.write("\t\treturn this." + _tempField +";");

    bw.newLine();

    bw.write("\t}");

    bw.newLine();

    }

    bw.newLine();

    bw.write("}");

    bw.newLine();

    bw.flush();

    bw.close();

    }

    /**

    *  构建Mapper文件

    *

    * @throws IOException

    */

    private void buildMapper()throws IOException {

    File folder =new File(mapper_path);

    if ( !folder.exists() ) {

    folder.mkdirs();

    }

    File mapperFile =new File(mapper_path, mapperName +".java");

    BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperFile),"utf-8"));

    bw.write("package " + mapper_package +";");

    bw.newLine();

    bw.newLine();

    bw.write("import " + bean_package +"." + beanName +";");

    bw.newLine();

    bw.write("import org.apache.ibatis.annotations.Param;");

    bw = buildClassComment(bw, mapperName +"数据库操作接口类");

    bw.newLine();

    bw.newLine();

    //      bw.write("public interface " + mapperName + " extends " + mapper_extends + " {");

    bw.write("public interface " + mapperName +"{");

    bw.newLine();

    bw.newLine();

    // ----------定义Mapper中的方法Begin----------

    bw = buildMethodComment(bw,"查询(根据主键ID查询)");

    bw.newLine();

    bw.write("\t" + beanName +"  selectByPrimaryKey ( @Param(\"id\") Long id );");

    bw.newLine();

    bw = buildMethodComment(bw,"删除(根据主键ID删除)");

    bw.newLine();

    bw.write("\t" +"int deleteByPrimaryKey ( @Param(\"id\") Long id );");

    bw.newLine();

    bw = buildMethodComment(bw,"添加");

    bw.newLine();

    bw.write("\t" +"int insert( " + beanName +" record );");

    bw.newLine();

    bw = buildMethodComment(bw,"添加 (匹配有值的字段)");

    bw.newLine();

    bw.write("\t" +"int insertSelective( " + beanName +" record );");

    bw.newLine();

    bw = buildMethodComment(bw,"修改 (匹配有值的字段)");

    bw.newLine();

    bw.write("\t" +"int updateByPrimaryKeySelective( " + beanName +" record );");

    bw.newLine();

    bw = buildMethodComment(bw,"修改(根据主键ID修改)");

    bw.newLine();

    bw.write("\t" +"int updateByPrimaryKey ( " + beanName +" record );");

    bw.newLine();

    // ----------定义Mapper中的方法End----------

    bw.newLine();

    bw.write("}");

    bw.flush();

    bw.close();

    }

    /**

    *  构建实体类映射XML文件

    *

    * @param columns

    * @param types

    * @param comments

    * @throws IOException

    */

    private void buildMapperXml( List columns, List types, List comments )throws IOException {

    File folder =new File(xml_path);

    if ( !folder.exists() ) {

    folder.mkdirs();

    }

    File mapperXmlFile =new File(xml_path, mapperName +".xml");

    BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperXmlFile)));

    bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

    bw.newLine();

    bw.write(""-//mybatis.org//DTD Mapper 3.0//EN\" ");

    bw.newLine();

    bw.write("    \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");

    bw.newLine();

    bw.write("");

    bw.newLine();

    bw.newLine();

    /*bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t");

    bw.newLine();

    bw.write("\t\t");

    bw.newLine();

    int size = columns.size();

    for ( int i = 1 ; i < size ; i++ ) {

    bw.write("\t\t");

    bw.newLine();

    bw.write("\t\t

    + this.processField(columns.get(i)) + "\" column=\"" + columns.get(i) + "\" />");

    bw.newLine();

    }

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    bw.newLine();*/

    // 下面开始写SqlMapper中的方法

    // this.outputSqlMapperMethod(bw, columns, types);

    buildSQL(bw, columns, types);

    bw.write("");

    bw.flush();

    bw.close();

    }

    private void buildSQL( BufferedWriter bw, List columns, List types )throws IOException {

    int size = columns.size();

    // 通用结果列

    bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t id,");

    for (int i =1 ; i < size ; i++ ) {

    bw.write("\t" + columns.get(i));

    if ( i != size -1 ) {

    bw.write(",");

    }

    }

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    // 查询(根据主键ID查询)

    bw.write("\t");

    bw.newLine();

    bw.write("\t

    + processResultMapId(beanName) +"\" parameterType=\"java.lang." + processType(types.get(0)) +"\">");

    bw.newLine();

    bw.write("\t\t SELECT");

    bw.newLine();

    bw.write("\t\t ");

    bw.newLine();

    bw.write("\t\t FROM " + tableName);

    bw.newLine();

    bw.write("\t\t WHERE " + columns.get(0) +" = #{" + processField(columns.get(0)) +"}");

    bw.newLine();

    bw.write("\t

    ");

    bw.newLine();

    bw.newLine();

    // 查询完

    // 删除(根据主键ID删除)

    bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t DELETE FROM " + tableName);

    bw.newLine();

    bw.write("\t\t WHERE " + columns.get(0) +" = #{" + processField(columns.get(0)) +"}");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    // 删除完

    // 添加insert方法

    bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t INSERT INTO " + tableName);

    bw.newLine();

    bw.write(" \t\t(");

    for (int i =0 ; i < size ; i++ ) {

    bw.write(columns.get(i));

    if ( i != size -1 ) {

    bw.write(",");

    }

    }

    bw.write(") ");

    bw.newLine();

    bw.write("\t\t VALUES ");

    bw.newLine();

    bw.write(" \t\t(");

    for (int i =0 ; i < size ; i++ ) {

    bw.write("#{" + processField(columns.get(i)) +"}");

    if ( i != size -1 ) {

    bw.write(",");

    }

    }

    bw.write(") ");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    // 添加insert完

    //---------------  insert方法(匹配有值的字段)

    bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t INSERT INTO " + tableName);

    bw.newLine();

    bw.write("\t\t ");

    bw.newLine();

    String tempField =null;

    for (int i =0 ; i < size ; i++ ) {

    tempField = processField(columns.get(i));

    bw.write("\t\t\t");

    bw.newLine();

    bw.write("\t\t\t\t " + columns.get(i) +",");

    bw.newLine();

    bw.write("\t\t\t");

    bw.newLine();

    }

    bw.newLine();

    bw.write("\t\t ");

    bw.newLine();

    bw.write("\t\t ");

    bw.newLine();

    tempField =null;

    for (int i =0 ; i < size ; i++ ) {

    tempField = processField(columns.get(i));

    bw.write("\t\t\t");

    bw.newLine();

    bw.write("\t\t\t\t #{" + tempField +"},");

    bw.newLine();

    bw.write("\t\t\t");

    bw.newLine();

    }

    bw.write("\t\t ");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    //---------------  完毕

    // 修改update方法

    bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t UPDATE " + tableName);

    bw.newLine();

    bw.write(" \t\t ");

    bw.newLine();

    tempField =null;

    for (int i =1 ; i < size ; i++ ) {

    tempField = processField(columns.get(i));

    bw.write("\t\t\t");

    bw.newLine();

    bw.write("\t\t\t\t " + columns.get(i) +" = #{" + tempField +"},");

    bw.newLine();

    bw.write("\t\t\t");

    bw.newLine();

    }

    bw.newLine();

    bw.write(" \t\t ");

    bw.newLine();

    bw.write("\t\t WHERE " + columns.get(0) +" = #{" + processField(columns.get(0)) +"}");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    // update方法完毕

    // ----- 修改(匹配有值的字段)

    bw.write("\t");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.write("\t\t UPDATE " + tableName);

    bw.newLine();

    bw.write("\t\t SET ");

    bw.newLine();

    tempField =null;

    for (int i =1 ; i < size ; i++ ) {

    tempField = processField(columns.get(i));

    bw.write("\t\t\t " + columns.get(i) +" = #{" + tempField +"}");

    if ( i != size -1 ) {

    bw.write(",");

    }

    bw.newLine();

    }

    bw.write("\t\t WHERE " + columns.get(0) +" = #{" + processField(columns.get(0)) +"}");

    bw.newLine();

    bw.write("\t");

    bw.newLine();

    bw.newLine();

    }

    /**

    *  获取所有的数据库表注释

    *

    * @return

    * @throws SQLException

    */

    private Map getTableComment()throws SQLException {

    Map maps =new HashMap();

    PreparedStatement pstate = conn.prepareStatement("show table status");

    ResultSet results = pstate.executeQuery();

    while ( results.next() ) {

    String tableName = results.getString("NAME");

    String comment = results.getString("COMMENT");

    maps.put(tableName, comment);

    }

    return maps;

    }

    public void generate()throws ClassNotFoundException, SQLException, IOException {

    init();

    String prefix ="show full fields from ";

    List columns =null;

    List types =null;

    List comments =null;

    PreparedStatement pstate =null;

    List tables = getTables();

    Map tableComments = getTableComment();

    for ( String table : tables ) {

    columns =new ArrayList();

    types =new ArrayList();

    comments =new ArrayList();

    pstate = conn.prepareStatement(prefix + table);

    ResultSet results = pstate.executeQuery();

    while ( results.next() ) {

    columns.add(results.getString("FIELD"));

    types.add(results.getString("TYPE"));

    comments.add(results.getString("COMMENT"));

    }

    tableName = table;

    processTable(table);

    //          this.outputBaseBean();

    String tableComment = tableComments.get(tableName);

    buildEntityBean(columns, types, comments, tableComment);

    buildMapper();

    buildMapperXml(columns, types, comments);

    }

    conn.close();

    }

    public static void main( String[] args ) {

    try {

    new EntityUtil().generate();

    // 自动打开生成文件的目录

    Runtime.getRuntime().exec("cmd /c start explorer D:\\");

    }catch ( ClassNotFoundException e ) {

    e.printStackTrace();

    }catch ( SQLException e ) {

    e.printStackTrace();

    }catch ( IOException e ) {

    e.printStackTrace();

    }

    }

    }

    展开全文
  • 用XStream写个demo给大家看看:maven依赖:com.thoughtworks.xstreamxstream1.3.1xpp3xpp31.1.4c三个:Student.javapackage com.simpco.xstreamtest;import com.thoughtworks.xstream.annotations.XStreamAlias;@...

    用XStream写个demo给大家看看:

    maven依赖:

    com.thoughtworks.xstream

    xstream

    1.3.1

    xpp3

    xpp3

    1.1.4c

    三个类:

    Student.javapackage com.simpco.xstreamtest;

    import com.thoughtworks.xstream.annotations.XStreamAlias;

    @XStreamAlias("Student")

    public class Student {

    private String name;

    private String sex;

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    public String getSex() {

    return sex;

    }

    public void setSex(String sex) {

    this.sex = sex;

    }

    public Student() {

    super();

    }

    @Override

    public String toString() {

    return "Student [name=" + name + ", sex=" + sex + "]";

    }

    }

    Root.javapackage com.simpco.xstreamtest;

    import java.util.ArrayList;

    import java.util.List;

    import com.thoughtworks.xstream.annotations.XStreamAlias;

    @XStreamAlias("Root")

    public class Root {

    @XStreamAlias("StudentList")

    private List studentList;

    public List getStudentList() {

    return studentList;

    }

    public void setStudentList(List studentList) {

    this.studentList = studentList;

    }

    public void addStudent(Student student){

    if(studentList==null){

    studentList = new ArrayList();

    }

    studentList.add(student);

    }

    }

    运行 App.javapackage com.simpco.xstreamtest;

    import com.thoughtworks.xstream.XStream;

    /**

    * Hello world!

    *

    */

    public class App {

    public static void main( String[] args ){

    XStream xstream = new XStream();

    Root root = new Root();

    Student student = new Student();

    student.setName("张三");

    student.setSex("男");

    root.addStudent(student);

    Student student1 = new Student();

    student1.setName("李四");

    student1.setSex("女");

    root.addStudent(student1);

    // xstream.alias("root", Root.class);

    // xstream.alias("Student", Student.class);

    // Annotations.configureAliases(xstream, Student.class);

    xstream.processAnnotations(Root.class);

    xstream.processAnnotations(Student.class);//声明使用Student中的注解别名

    String xml = xstream.toXML(root);

    String top = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

    System.out.println(top+xml);

    // Root rootObj = (Root)xstream.fromXML(xml);

    // System.out.println(JSON.toJSONString(rootObj));

    }

    }

    预期结果:<?xml version="1.0" encoding="UTF-8"?>

    张三

    李四

    展开全文
  • 摘要:①读取XML文件生成pojo对象;②将对象信息保存到xml中。步骤:①新建一个普通的java类BasePage;packagecom.test.selenium.pages;importjava.util.Map;importcom.thoughtworks.xstream.annotations....

    摘要:①读取XML文件,生成pojo对象;②将对象信息保存到xml中。

    步骤:

    ①新建一个普通的java类BasePage;

    packagecom.test.selenium.pages;importjava.util.Map;importcom.thoughtworks.xstream.annotations.XStreamAlias;

    @XStreamAlias("basePage")public classBasePage {

    @XStreamAlias("pageName")privateString pageName;

    @XStreamAlias("pageXpaths")private MappageXpaths;publicBasePage() {}public BasePage(String pageName, MappageXpaths) {super();this.pageName =pageName;this.pageXpaths =pageXpaths;

    }publicString getPageXpath(String name) {returnpageXpaths.get(name);

    }publicString getPageName() {returnpageName;

    }public voidsetPageName(String pageName) {this.pageName =pageName;

    }public MapgetPageXpaths() {returnpageXpaths;

    }public void setPageXpaths(MappageXpaths) {this.pageXpaths =pageXpaths;

    }

    }

    ②新建一个page.xml;

    pageName

    name2

    value2

    name1

    value1

    ③封装XMLTools类;

    packagecom.test.selenium.utils;importjava.io.FileInputStream;importjava.io.FileOutputStream;importcom.thoughtworks.xstream.XStream;importcom.thoughtworks.xstream.annotations.XStreamAlias;importcom.thoughtworks.xstream.io.xml.DomDriver;public classXMLTools {/*** 将对象信息保存到xml中

    *

    *@paramentity

    *@paramfile*/

    public static void saveToXml(T entity, String file) throwsException {

    XStream stream= new XStream(new DomDriver("utf-8"));

    stream.autodetectAnnotations(true);

    FileOutputStream fileOutputStream= newFileOutputStream(file);

    stream.toXML(entity, fileOutputStream);

    }/*** 从配置文件中读取配置,并自动转换为对应的对象

    *

    *@paramclazz

    *@paramfile

    *@return对象

    *@throwsException*/@SuppressWarnings({"unchecked"})public static T getFromXml(Class clazz, String file) throwsException {

    XStream xStream= new XStream(new DomDriver("utf-8"));

    xStream.autodetectAnnotations(true);

    FileInputStream fileInputStream= null;

    T entity= null;

    fileInputStream= newFileInputStream(file);

    String alias= "";if (clazz.isAnnotationPresent(XStreamAlias.class)) {

    alias= clazz.getAnnotation(XStreamAlias.class).value();//获取POJO里面的@XStreamAlias()的值

    }

    xStream.alias(alias, clazz);

    entity=(T) xStream.fromXML(fileInputStream);returnentity;

    }

    }

    ④工具类XMLTools的测试类;

    packagecom.test.selenium.test;importjava.util.HashMap;importjava.util.Map;importorg.junit.Test;importcom.test.selenium.pages.BasePage;importcom.test.selenium.utils.XMLTools;public classXMLToolsTest {

    @Testpublic voidtestGetPage() {

    BasePage basePage= null;try{

    basePage= XMLTools.getFromXml(BasePage.class, "pages/page.xml");

    System.out.println(basePage.getPageName());for (Map.Entrypath:basePage.getPageXpaths().entrySet()){

    System.out.println(path.getKey());

    System.out.println(path.getValue());

    }

    }catch(Exception e) {

    e.printStackTrace();

    }

    }

    @Testpublic voidtestSavePage(){

    Map paths = new HashMap<>();

    paths.put("name1", "value1");

    paths.put("name2", "value2");

    BasePage basePage= new BasePage("pageName", paths);try{

    XMLTools.saveToXml(basePage,"pages/page2.xml");

    }catch(Exception e) {

    e.printStackTrace();

    }

    }

    }

    ⑤运行结果;

    --testGetPage:

    pageName

    name2

    value2

    name1

    value1

    --testSavePage:

    pageName

    name2

    value2

    name1

    value1

    展开全文
  • 这是一个java操作xml文件工具类,最大的亮点在于能够通过工具类直接生成xml同样层次结构的java代码,也就是说,只要你定义好了xml的模板,就能一键生成java代码。省下了自己再使用工具类写代码的时间,极大得提高...

    这是一个java操作xml文件的工具类,最大的亮点在于能够通过工具类直接生成xml同样层次结构的java代码,也就是说,只要你定义好了xml的模板,就能一键生成java代码。省下了自己再使用工具类写代码的时间,极大得提高了效率。

    首先来看看工具类代码

    package com.lfq.createXml;

    import java.io.ByteArrayInputStream;

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.OutputStream;

    import java.io.StringReader;

    import java.io.StringWriter;

    import java.io.UnsupportedEncodingException;

    import java.util.ArrayList;

    import java.util.List;

    import java.util.Properties;

    import javax.xml.XMLConstants;

    import javax.xml.parsers.DocumentBuilder;

    import javax.xml.parsers.DocumentBuilderFactory;

    import javax.xml.parsers.ParserConfigurationException;

    import javax.xml.transform.OutputKeys;

    import javax.xml.transform.Result;

    import javax.xml.transform.Source;

    import javax.xml.transform.Transformer;

    import javax.xml.transform.TransformerException;

    import javax.xml.transform.TransformerFactory;

    import javax.xml.transform.dom.DOMSource;

    import javax.xml.transform.stream.StreamResult;

    import javax.xml.transform.stream.StreamSource;

    import javax.xml.validation.Schema;

    import javax.xml.validation.SchemaFactory;

    import javax.xml.validation.Validator;

    import org.apache.commons.lang3.StringUtils;

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.Node;

    import org.w3c.dom.NodeList;

    import org.xml.sax.SAXException;

    /**

    * 操作xml文件以及生成java代码的工具

    * @author lfq

    * @since 1.0, Jun 12, 2007

    */

    public final class XmlUtils {

    private static final String XMLNS_XSI = "xmlns:xsi";

    private static final String XSI_SCHEMA_LOCATION = "xsi:schemaLocation";

    private static final String LOGIC_YES = "yes";

    private static final String DEFAULT_ENCODE = "UTF-8";

    private static final String REG_INVALID_CHARS = "\\d+;";

    /**

    * Creates a new document instance.

    *

    * @return a new document instance

    * @throws XmlException problem creating a new document

    */

    public static Document newDocument() throws XmlException {

    Document doc = null;

    try {

    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()

    .newDocument();

    } catch (ParserConfigurationException e) {

    throw new XmlException(e);

    }

    return doc;

    }

    /**

    * Parses the content of the given XML file as an XML document.

    *

    * @param file the XML file instance

    * @return the document instance representing the entire XML document

    * @throws XmlException problem parsing the XML file

    */

    public static Document getDocument(File file) throws XmlException {

    InputStream in = getInputStream(file);

    return getDocument(in);

    }

    /**

    * Parses the content of the given stream as an XML document.

    *

    * @param in the XML file input stream

    * @return the document instance representing the entire XML document

    * @throws XmlException problem parsing the XML input stream

    */

    public static Document getDocument(InputStream in) throws XmlException {

    Document doc = null;

    try {

    DocumentBuilder builder = DocumentBuilderFactory.newInstance()

    .newDocumentBuilder();

    doc = builder.parse(in);

    } catch (ParserConfigurationException e) {

    throw new XmlException(e);

    } catch (SAXException e) {

    throw new XmlException(XmlException.XML_PARSE_ERROR, e);

    } catch (IOException e) {

    throw new XmlException(XmlException.XML_READ_ERROR, e);

    } finally {

    if (in != null) {

    try {

    in.close();

    } catch (IOException e) {

    // nothing to do

    }

    }

    }

    return doc;

    }

    /**

    * Creates a root element as well as a new document with specific tag name.

    *

    * @param tagName the name of the root element

    * @return a new element instance

    * @throws XmlException problem generating a new document

    */

    public static Element createRootElement(String tagName) throws XmlException {

    Document doc = newDocument();

    Element root = doc.createElement(tagName);

    doc.appendChild(root);

    return root;

    }

    /**

    * Gets the root element from input stream.

    *

    * @param in the XML file input stream

    * @return the root element of parsed document

    * @throws XmlException problem parsing the XML file input stream

    */

    public static Element getRootElementFromStream(InputStream in)

    throws XmlException {

    return getDocument(in).getDocumentElement();

    }

    /**

    * Gets the root element from given XML file.

    *

    * @param fileName the name of the XML file

    * @return the root element of parsed document

    * @throws XmlException problem parsing the XML file

    */

    public static Element getRootElementFromFile(File file)

    throws XmlException {

    return getDocument(file).getDocumentElement();

    }

    /**

    * Gets the root element from the given XML payload.

    *

    * @param payload the XML payload representing the XML file.

    * @return the root element of parsed document

    * @throws XmlException problem parsing the XML payload

    */

    public static Element getRootElementFromString(String payload)

    throws XmlException {

    if (payload == null || payload.trim().length() < 1) {

    throw new XmlException(XmlException.XML_PAYLOAD_EMPTY);

    }

    byte[] bytes = null;

    try {

    bytes = payload.getBytes(DEFAULT_ENCODE);

    } catch (UnsupportedEncodingException e) {

    throw new XmlException(XmlException.XML_ENCODE_ERROR, e);

    }

    InputStream in = new ByteArrayInputStream(bytes);

    return getDocument(in).getDocumentElement();

    }

    /**

    * Gets the descendant elements list from the parent element.

    *

    * @param parent the parent element in the element tree

    * @param tagName the specified tag name

    * @return the NOT NULL descendant elements list

    */

    public static List getElements(Element parent, String tagName) {

    NodeList nodes = parent.getElementsByTagName(tagName);

    List elements = new ArrayList();

    for (int i = 0; i < nodes.getLength(); i++) {

    Node node = nodes.item(i);

    if (node instanceof Element) {

    elements.add((Element) node);

    }

    }

    return elements;

    }

    /**

    * Gets the immediately descendant element from the parent element.

    *

    * @param parent the parent element in the element tree

    * @param tagName the specified tag name.

    * @return immediately descendant element of parent element, NULL otherwise.

    */

    public static Element getElement(Element parent, String tagName) {

    List children = getElements(parent, tagName);

    if (children.isEmpty()) {

    return null;

    } else {

    return children.get(0);

    }

    }

    /**

    * Gets the immediately child elements list from the parent element.

    *

    * @param parent the parent element in the element tree

    * @param tagName the specified tag name

    * @return the NOT NULL immediately child elements list

    */

    public static List getChildElements(Element parent, String tagName) {

    NodeList nodes = parent.getElementsByTagName(tagName);

    List elements = new ArrayList();

    for (int i = 0; i < nodes.getLength(); i++) {

    Node node = nodes.item(i);

    if (node instanceof Element && node.getParentNode() == parent) {

    elements.add((Element) node);

    }

    }

    return elements;

    }

    /**

    * Gets the immediately child element from the parent element.

    *

    * @param parent the parent element in the element tree

    * @param tagName the specified tag name

    * @return immediately child element of parent element, NULL otherwise

    */

    public static Element getChildElement(Element parent, String tagName) {

    List children = getChildElements(parent, tagName);

    if (children.isEmpty()) {

    return null;

    } else {

    return children.get(0);

    }

    }

    /**

    * Gets the value of the child element by tag name under the given parent

    * element. If there is more than one child element, return the value of the

    * first one.

    *

    * @param parent the parent element

    * @param tagName the tag name of the child element

    * @return value of the first child element, NULL if tag not exists

    */

    public static String getElementValue(Element parent, String tagName) {

    String value = null;

    Element element = getElement(parent, tagName);

    if (element != null) {

    value = element.getTextContent();

    }

    return value;

    }

    /**

    * Appends the child element to the parent element.

    *

    * @param parent the parent element

    * @param tagName the child element name

    * @return the child element added to the parent element

    */

    public static Element appendElement(Element parent, String tagName) {

    Element child = parent.getOwnerDocument().createElement(tagName);

    parent.appendChild(child);

    return child;

    }

    /**

    * Appends the child element as well as value to the parent element.

    *

    * @param parent the parent element

    * @param tagName the child element name

    * @param value the child element value

    * @return the child element added to the parent element

    */

    public static Element appendElement(Element parent, String tagName,

    String value) {

    Element child = appendElement(parent, tagName);

    child.setTextContent(value);

    return child;

    }

    /**

    * Appends another element as a child element.

    *

    * @param parent the parent element

    * @param child the child element to append

    */

    public static void appendElement(Element parent, Element child) {

    Node tmp = parent.getOwnerDocument().importNode(child, true);

    parent.appendChild(tmp);

    }

    /**

    * Appends the CDATA element to the parent element.

    *

    * @param parent the parent element

    * @param tagName the CDATA element name

    * @param value the CDATA element value

    * @return the CDATA element added to the parent element

    */

    public static Element appendCDATAElement(Element parent, String tagName,

    String value) {

    Element child = appendElement(parent, tagName);

    if (value == null) { // avoid "null" word in the XML payload

    value = "";

    }

    Node cdata = child.getOwnerDocument().createCDATASection(value);

    child.appendChild(cdata);

    return child;

    }

    /**

    * Converts the Node/Element instance to XML payload.

    *

    * @param node the node/element instance to convert

    * @return the XML payload representing the node/element

    * @throws XmlException problem converting XML to string

    */

    public static String childNodeToString(Node node) throws XmlException {

    String payload = null;

    try {

    Transformer tf = TransformerFactory.newInstance().newTransformer();

    Properties props = tf.getOutputProperties();

    props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);

    tf.setOutputProperties(props);

    StringWriter writer = new StringWriter();

    tf.transform(new DOMSource(node), new StreamResult(writer));

    payload = writer.toString();

    payload = payload.replaceAll(REG_INVALID_CHARS, " ");

    } catch (TransformerException e) {

    throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);

    }

    return payload;

    }

    /**

    * Converts the Node/Document/Element instance to XML payload.

    *

    * @param node the node/document/element instance to convert

    * @return the XML payload representing the node/document/element

    * @throws XmlException problem converting XML to string

    */

    public static String nodeToString(Node node) throws XmlException {

    String payload = null;

    try {

    Transformer tf = TransformerFactory.newInstance().newTransformer();

    Properties props = tf.getOutputProperties();

    props.setProperty(OutputKeys.INDENT, LOGIC_YES);

    props.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODE);

    tf.setOutputProperties(props);

    StringWriter writer = new StringWriter();

    tf.transform(new DOMSource(node), new StreamResult(writer));

    payload = writer.toString();

    payload = payload.replaceAll(REG_INVALID_CHARS, " ");

    } catch (TransformerException e) {

    throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);

    }

    return payload;

    }

    /**

    * Converts the an XML file to XML payload.

    *

    * @param file the XML file instance

    * @return the XML payload representing the XML file

    * @throws XmlException problem transforming XML to string

    */

    public static String xmlToString(File file) throws XmlException {

    Element root = getRootElementFromFile(file);

    return nodeToString(root);

    }

    /**

    * Converts the an XML file input stream to XML payload.

    *

    * @param in the XML file input stream

    * @return the payload represents the XML file

    * @throws XmlException problem transforming XML to string

    */

    public static String xmlToString(InputStream in) throws XmlException {

    Element root = getRootElementFromStream(in);

    return nodeToString(root);

    }

    /**

    * Saves the node/document/element as XML file.

    *

    * @param doc the XML node/document/element to save

    * @param file the XML file to save

    * @throws XmlException problem persisting XML file

    */

    public static void saveToXml(Node doc, File file) throws XmlException {

    OutputStream out = null;

    try {

    Transformer tf = TransformerFactory.newInstance().newTransformer();

    Properties props = tf.getOutputProperties();

    props.setProperty(OutputKeys.METHOD, XMLConstants.XML_NS_PREFIX);

    props.setProperty(OutputKeys.INDENT, LOGIC_YES);

    tf.setOutputProperties(props);

    DOMSource dom = new DOMSource(doc);

    out = getOutputStream(file);

    Result result = new StreamResult(out);

    tf.transform(dom, result);

    } catch (TransformerException e) {

    throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);

    } finally {

    if (out != null) {

    try {

    out.close();

    } catch (IOException e) {

    // nothing to do

    }

    }

    }

    }

    /**

    * Validates the element tree context via given XML schema file.

    *

    * @param doc the XML document to validate

    * @param schemaFile the XML schema file instance

    * @throws XmlException error occurs if the schema file not exists

    */

    public static void validateXml(Node doc, File schemaFile)

    throws XmlException {

    validateXml(doc, getInputStream(schemaFile));

    }

    /**

    * Validates the element tree context via given XML schema file.

    *

    * @param doc the XML document to validate

    * @param schemaStream the XML schema file input stream

    * @throws XmlException error occurs if validation fail

    */

    public static void validateXml(Node doc, InputStream schemaStream)

    throws XmlException {

    try {

    Source source = new StreamSource(schemaStream);

    Schema schema = SchemaFactory.newInstance(

    XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);

    Validator validator = schema.newValidator();

    validator.validate(new DOMSource(doc));

    } catch (SAXException e) {

    throw new XmlException(XmlException.XML_VALIDATE_ERROR, e);

    } catch (IOException e) {

    throw new XmlException(XmlException.XML_READ_ERROR, e);

    } finally {

    if (schemaStream != null) {

    try {

    schemaStream.close();

    } catch (IOException e) {

    // nothing to do

    }

    }

    }

    }

    /**

    * Transforms the XML content to XHTML/HTML format string with the XSL.

    *

    * @param payload the XML payload to convert

    * @param xsltFile the XML stylesheet file

    * @return the transformed XHTML/HTML format string

    * @throws XmlException problem converting XML to HTML

    */

    public static String xmlToHtml(String payload, File xsltFile)

    throws XmlException {

    String result = null;

    try {

    Source template = new StreamSource(xsltFile);

    Transformer transformer = TransformerFactory.newInstance()

    .newTransformer(template);

    Properties props = transformer.getOutputProperties();

    props.setProperty(OutputKeys.OMIT_XML_DECLARATION, LOGIC_YES);

    transformer.setOutputProperties(props);

    StreamSource source = new StreamSource(new StringReader(payload));

    StreamResult sr = new StreamResult(new StringWriter());

    transformer.transform(source, sr);

    result = sr.getWriter().toString();

    } catch (TransformerException e) {

    throw new XmlException(XmlException.XML_TRANSFORM_ERROR, e);

    }

    return result;

    }

    /**

    * Sets the namespace to specific element.

    *

    * @param element the element to set

    * @param namespace the namespace to set

    * @param schemaLocation the XML schema file location URI

    */

    public static void setNamespace(Element element, String namespace,

    String schemaLocation) {

    element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,

    XMLConstants.XMLNS_ATTRIBUTE, namespace);

    element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, XMLNS_XSI,

    XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);

    element.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,

    XSI_SCHEMA_LOCATION, schemaLocation);

    }

    /**

    * Encode the XML payload to legality character.

    *

    * @param payload the XML payload to encode

    * @return the encoded XML payload

    * @throws XmlException problem encoding the XML payload

    */

    public static String encodeXml(String payload) throws XmlException {

    Element root = createRootElement(XMLConstants.XML_NS_PREFIX);

    root.setTextContent(payload);

    return childNodeToString(root.getFirstChild());

    }

    private static InputStream getInputStream(File file) throws XmlException {

    InputStream in = null;

    try {

    in = new FileInputStream(file);

    } catch (FileNotFoundException e) {

    throw new XmlException(XmlException.FILE_NOT_FOUND, e);

    }

    return in;

    }

    private static OutputStream getOutputStream(File file) throws XmlException {

    OutputStream in = null;

    try {

    in = new FileOutputStream(file);

    } catch (FileNotFoundException e) {

    throw new XmlException(XmlException.FILE_NOT_FOUND, e);

    }

    return in;

    }

    /**

    * @Desc 把实体类中有的字段直接转为xml节点

    * @author LV_FQ

    * @date 2016年12月15日

    * @param parent

    * @param formMap

    * @param fields

    */

    public static void entityToXml(Element parent, String... fields){

    for(String field : fields){

    String temp = "XmlUtils.appendElement(root, \"" + field + "\", decHeadFormMap.getStr(\"field\"));";

    System.out.println(temp);

    XmlUtils.appendElement(parent, field, "取值");

    }

    }

    /**

    * @Desc 根据xml生成java代码

    * @author LV_FQ

    * @date 2016年12月16日

    * @param file xml文件

    */

    public static void createJavaCode(File file){

    XMLToJavaUtils.createJavaCode(file);

    }

    }

    class XmlException extends RuntimeException {

    private static final long serialVersionUID = 381260478228427716L;

    public static final String XML_PAYLOAD_EMPTY = "xml.payload.empty";

    public static final String XML_ENCODE_ERROR = "xml.encoding.invalid";

    public static final String FILE_NOT_FOUND = "xml.file.not.found";

    public static final String XML_PARSE_ERROR = "xml.parse.error";

    public static final String XML_READ_ERROR = "xml.read.error";

    public static final String XML_VALIDATE_ERROR = "xml.validate.error";

    public static final String XML_TRANSFORM_ERROR = "xml.transform.error";

    public XmlException() {

    super();

    }

    public XmlException(String key, Throwable cause) {

    super(key, cause);

    }

    public XmlException(String key) {

    super(key);

    }

    public XmlException(Throwable cause) {

    super(cause);

    }

    }

    /**

    * @Desc 根据xml的格式生成xml的对应的java生成代码

    * @author LV_FQ

    * @date 2016年12月16日 下午2:08:38

    * @version 1.0

    *

    */

    class XMLToJavaUtils {

    public static void createJavaCode(File file) {

    try {

    //File file = new File("C:/Users/SUCCESS/Desktop/temp.xml");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    Document doc = dBuilder.parse(file);

    if (doc.hasChildNodes()) {

    printNote(doc.getChildNodes(), null);

    }

    } catch (Exception e) {

    e.printStackTrace();

    }

    }

    private static void printNote(NodeList nodeList, Node parent) {

    for (int i = 0; i < nodeList.getLength(); i++) {

    Node node = nodeList.item(i);

    if (node.getNodeType() == Node.ELEMENT_NODE) {

    if(parent == null){

    System.out.println("Element "+ getTagName(node.getNodeName())+" = XmlUtils.createRootElement(\""+ node.getNodeName() +"\");");

    }else{

    String temp = "XmlUtils.appendElement("+getTagName(parent == null? null : parent.getNodeName())+", \"" + node.getNodeName();

    if (node.hasChildNodes() && node.getChildNodes().getLength() > 1) {

    System.out.println();

    //非叶节点把节点的名称加上,以便子节点和父节点做关联

    temp = "Element " + getTagName(node.getNodeName()) + " = " + temp + "\");";

    }else{

    //叶节点把注释加上

    //temp += "\", \"value\");//" + node.getTextContent();

    temp += "\", \""+ node.getTextContent() +"\");";

    }

    System.out.println(temp);

    }

    if (node.hasChildNodes()) {

    printNote(node.getChildNodes(), node);

    }

    }

    }

    }

    /**

    * @Desc 把字符串第一个字母转小写

    * @author LV_FQ

    * @date 2016年12月16日

    * @param name

    * @return

    */

    private static String getTagName(String name){

    if(StringUtils.isBlank(name)){

    return "";

    }

    String temp = name;

    temp = temp.substring(0, 1).toLowerCase() + temp.substring(1);

    return temp;

    }

    }

    测试类

    package com.lfq.createXml;

    import java.io.File;

    import org.w3c.dom.Element;

    public class TestXml {

    public static void main(String[] args) {

    Element note = XmlUtils.createRootElement("note");

    XmlUtils.appendElement(note, "to", "George1");

    XmlUtils.appendElement(note, "from", "John2");

    XmlUtils.appendElement(note, "heading", "Reminder1");

    XmlUtils.appendElement(note, "body", "Don't forget the meeting!");

    XmlUtils.saveToXml(note, new File("/home/lv-success/Desktop/temp.xml"));

    //使用xml生成工具生成java代码(控制台输出)

    File file = new File("/home/lv-success/Desktop/temp.xml");

    XmlUtils.createJavaCode(file);

    }

    }

    从test中可以看出,工具类通过已有的操作xml文件的方法读取xml的结构,同时根据读取的节点内容直接把对于生成的方法打印到控制台中,如此嵌套打印,最终打印出这个xml文件的相同java层次结构的代码。

    如果对生成的java代码有不同要求,大家可以直接修改工具类中的生成java代码的方法。能生成自己最终要求最接近的代码最好,怎么方便怎么来哈。

    展开全文
  • 最近一直在做关于webservice 的项目...为什么要把XML转化为XSD文件呢,这是因为JAXB可以识别XSD文件,并将其转化为java对象,如何使用这个网址生成XSD文件呢?首先网址打开之后会出现上图界面,然后点击 XML to XSD...
  • 使用的所有工具和软件:IntelliJ IDEA,dom4j-1.6.1.jar;一、导入dom4j-1.6.1.jar二、创建Test测试三、导入各种需要使用的包import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;...
  • 使用 JAXB 工具根据 Java 类生成 XML 模式2010-06-10 18:24:26| 分类: web service |字号 订阅关键字: java to xml 使用 JAXB 工具根据 Java 类生成 XML 模式文件2008-10-31 20:02使用 JAXB 工具根据 Java 类生成 ...
  • 您使用DOM相关生成xml.下面是使用JAXP创建XML的一个小例子.import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers....
  • 最近一直在做关于webservice 的项目...为什么要把XML转化为XSD文件呢,这是因为JAXB可以识别XSD文件,并将其转化为java对象,如何使用这个网址生成XSD文件呢?首先网址打开之后会出现上图界面,然后点击 XML to XSD...
  • 生成xml文件有很多工具Java自己也可以一个节点一个节点的来生成,但效率低下,不方便结构化,也不通用。可以根据java类来自动生成对应结构化的xml文件的库很多,今天简单说一下xStream库,非常简单,但实用。如果...
  • 如何将此XML文件添加到classpath?命令行# java -classpath . dk.firma.klient.webservice.OiosiRaspClient的.classpath解决方法:你不能按照你想要的方式去做.您不能直接在命令行中添加.classpath文件(我猜是由...
  • java实体类生成xml工具

    2015-01-23 15:29:11
    /** * 实体类生成xml工具 * @author jermon */public class CrawlerJavaBean2Xml {// 文件头编码类型public static final String XML_HEAD_TYPE_UTF8 = "";public static final String XML_HEAD_TY
  • Java工具类_表结构自动生成对应的实体类、Mapper.xml文件、Dao类
  • 最近一直在做关于webservice 的项目,这种项目最麻烦的就是根据对方的要求产生...首先得感谢 博客 XML生成java类 提供了一个很好的XML转XSD的好工具,在线的:https://www.luxonsoftware.com 为什么要把XML转化为...
  • 目前现在有很多的mybatis自动生成代码的工具,典型的mybatis-generator插件,经配置生成文件直接便可以使用了。确实非常的方便和实用。但是在日常的开发当中,为了使项目简洁、清晰。让人一看就明白,排起错来也是...
  • 使用 JAXB 工具根据 Java 类生成 XML 模式文件2008-10-31 20:02使用 JAXB 工具根据 Java 类生成 XML 模式文件 使用 Java XML 绑定体系结构(JAXB)工具根据 Java 类生成 XML 模式文件。 在您开始之前 标识 Java...
  • xml文件是大家熟知的配置文件,我们当然可以通过java来对其创建删改查,比如说生成一个这 一、方法 1.创建文件 接下来我们模拟创建一个pom文件中的依赖 /** * 创建XML文档 */ public static void createXML...
  • 这是一个java操作xml文件工具类,最大的亮点在于能够通过工具类直接生成xml同样层次结构的java代码,也就是说,只要你定义好了xml的模板,就能一键生成java代码。省下了自己再使用工具类写代码的时间,极大得提高...
  • XML生成java代码工具

    2016-05-22 23:20:06
    可以通过xml文件直接生成对应的java类文件。 运行需要jre
  • 1、新建注解,区别字段与xml字段 /** * xml字段 */ @Target({ElementType.TYPE,ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME)...2、新建工具类 import org.jdom2.Document; import org.jdom2.Element
  • 目前现在有很多的mybatis自动生成代码的工具,典型的mybatis-generator插件,经配置生成文件直接便可以使用了。 确实非常的方便和实用。但是在日常的开发当中,为了使项目简洁、清晰。让人一看就明白,排起错来也...
  • 由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实体、DAO接口和Mapping映射文件。这样可以省去很多的功夫,将...
  • 参考:所需工具:步骤:1、在word中编辑好模版样式,设置好占位符,注意图片最好先黏上去2、在word中,文件-另存为-XML格式3、使用工具格式化上图的XML文件a.在表格数据的TR中加入 和#list>b.将XML文件中图片的...
  • 前面说过用Middelgen可以完成从数据库方案转化为hbm文件,然后通过hbm2java生成JAVA的实体。现在可以使用更加简单的办法,那就是借助于MyEclipse这个强大的开发工具。  我们已经做好了数据库设计,那么,接...
  • 由于是云桌面,再加上内网,代码搞不出来(莫怪小弟...第一参数是实体bean,第二个参数是一个传过来的名字(可有可无,我们项目需求的需要)第三个参数是文件生成的路径与文件名 希望对大家有用,拜拜。 ...
  • mybatis实体以及mapper映射xml文件及接口的自动生成类工具
  • JAXB(Java Architecture for XML Binding)是一种特殊的序列化/反序列化工具。它可以使XML数据以Java Objects的形式直接应用于Java程序之中,使Java Objects与XML数据之间的转换成为可能。在JAXB中将Java Objects到...
  • Java逆向生成实体:包括所需要的import,tag,字段注释,序列化等。配套的还有dao层,dao.xml,service层,serviceImpl的生成文件,在其他下载资源中。
  • 首先从https://jaxb.java.net/2.2.11/ 获取最新的jaxb 这里提供一个Schema文档用xjc工具生成java类 xjc工具基于此模式来绑定一个模式到Java类,xjc命令行接口的一些选项列在下表:-nv 对于输入的模式不执行严格的...
  • 将trang.jar和要解析的xml放在同一目录,在当前文件下执行如下命令,其中users.xsd为要生成的xsd文件名 java -jar trang.jar users.xml users.xsd 执行完上述命令后会在当前文件生成users.xsd,然后执行如下命令,...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 745
精华内容 298
关键字:

java生成xml文件工具类

java 订阅