Xmind转Excel测试用例 Java篇
目录
前言:
Excel用例模板如下:
XMind XML
XMind用例格式:
约束条件:
项目目录结构如下:
工具界面如下:
pom文件:
log4j2.xml:
UI类Excel2XMLUI 如下:
提示窗口UI类:
Excel工具类:
文件工具类:
Log类:
用例模板类:
Excel转XML类:
Xmind转Excel类:
XML2Excel 类:
前言:
最近公司整了个测试用例平台只支持Excel格式导入,但是现在都懒得用Excel写用例了,太麻烦而且慢,还是习惯用xmind思维导图方式写用例,又快结构又清晰。
Excel用例模板如下:
| 用例名称 | 前置条件 | 操作步骤 | 预期结果 | 优先级 | 所属模块 | 版本号 | 用例类型 | 关联需求 | 是否自动化 | 用例维护人 |
由于之前做过一版xmind转Excel用例的就是用例模板不一样,所以将以前的代码改了一下。说一下思路,xmind主要结构还是以xml来组织的一个xmind格式压缩包,我们可以把.xmind后缀改成.zip就可以看到xmind的整个文件结构了,可以看到xmind主要是由xml文件组织的,而整个导图的内容就在content.xml这个文件中,如下:
XMind XML
Xmind测试用例模板(备注中添加版本号、维护人工号、用例类型) 模块0 模块1 模块2 关联需求1 测试用例1--优先级高 单个测试步骤 单个测试结果 测试用例2--优先级中 1、多个测试步骤1 2、多个步骤2 测试结果1 测试结果2 测试用例3--优先级低 测试步骤 测试结果 关联需求2 测试用例1--优先级高 单个测试步骤 单个测试结果 测试用例2--优先级中 1、多个测试步骤1 2、多个步骤2 测试结果1 测试结果2 模块2 模块3 模块4 关联需求3 测试用例1--优先级高 单个测试步骤 单个测试结果 测试用例2--优先级中 1、多个测试步骤1 2、多个步骤2 测试结果1 测试结果2 测试用例3--优先级低 测试步骤 测试结果 关联需求4 测试用例1--优先级高 单个测试步骤 单个测试结果 测试用例2--优先级中 1、多个测试步骤1 2、多个步骤2 测试结果1 测试结果2 -1 版本号:V4.2 维护人:xxxx 用例类型:功能测试用例
所以我们要做的就是解析这个xml文件然后拿到相应节点的内容填充到相应的Excel单元格当中,可以看出文本类容主要集中在title标签中,xmind的xml路径比较深,没有做标记的话不好区分,俗话说没有规矩不成方圆,所以我们需要定义xmind用例的格式这样才好去解析它。
XMind用例格式:

约束条件:
1、旗帜表示模块
2、星星表示需求
3、数字图标表示用例和用例优先级(1:高 2:中 3:低)
4、在用例上加备注表示用例前置条件
5、用例下的第一个分支表示测试步骤,多个用例步骤,在第一个分支加上多个步骤即可;
第二个分支表示期望结果(期望结果可以有多个,即多个分支可以表示多个步骤)
6、在中心主题上面加个备注就可以,注意用英文的冒号没备注的顺序不要乱了,按版本号、维护人、用例类型的顺序写备注
ps:需求不能为空不然识别不到后面的用例
项目目录结构如下:

工具界面如下:

pom文件:
4.0.0 com testlink 0.0.1-SNAPSHOT org.apache.maven.plugins maven-compiler-plugin 7 7 maven-assembly-plugin jar-with-dependencies com.testlink.Excel2XMLUI make-assembly package single jar testlink http://maven.apache.org UTF-8 junit junit 4.13.2 test org.apache.maven.plugins maven-assembly-plugin 3.0.0 org.apache.logging.log4j log4j-core 2.11.0 org.apache.logging.log4j log4j-api 2.11.0 org.dom4j dom4j 2.1.0 org.apache.poi poi 3.17 org.apache.poi poi-ooxml 3.17 org.apache.xmlbeans xmlbeans 2.6.0
log4j2.xml:
logs log k
UI类Excel2XMLUI 如下:
package com.testlink;import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.WindowConstants;import org.dom4j.DocumentException;public class Excel2XMLUI extends JFrame implements ActionListener, DropTargetListener, TestCaseLog {String filePath = null;// 文件路径String inputFile = null;// 输入文件File outPutFile = null;// 输出文件String inPutFileName = null;// 输入文件名称String xmindExcelFile = null;// 输出的xmind转换后的Excel测试用例File chooserFile = null;// 选择的文件File inPutXMLFile = null;// 输入的xml文件File inPutXmindFile = null;// 输入的xmind文件public static void main(String[] args) {new Excel2XMLUI(true);}/*** */DropTarget dropTarget;// 拖曳对象JRadioButton excel2XmlR;// Excel2xml单选框JRadioButton xml2ExcelR;// xml2Excel单选框JRadioButton xmind2ExcelR;// JLabel testcaseVersion;//设置用例版本// JTextField testcaseVerText;// 路径显示文本框// JLabel testcaseAuthor;//设置用例维护人// JTextField testcaseAuthorText;//设置用例维护人文本// JButton excelButton;// 打开文件按钮JButton fileButton;JTextField fileFilePath;// 路径显示文本框JTextField xmlFilePath;// xml文件路径JFileChooser jFileChooser;// 选择的文件或者拖入的文件JButton covertButton;// 转换按钮private static final long serialVersionUID = 9134604994013111325L;public Excel2XMLUI(boolean isShowWindow) {// JLabel exLabel = new JLabel("Excel->XML");dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true);// 实现拖曳效果excel2XmlR = new JRadioButton("Excel=>XML");xml2ExcelR = new JRadioButton("XML=>Excel");xmind2ExcelR = new JRadioButton("Xmind=>Excel");// testcaseVersion=new JLabel("版本号:");// testcaseVerText=new JTextField("请输入版本号",5);// testcaseVerText.setForeground(Color.GRAY);//// testcaseAuthor=new JLabel("用例维护者:");// testcaseAuthorText=new JTextField("请输入工号",5);// testcaseAuthorText.setForeground(Color.GRAY);fileFilePath = new JTextField("请拖放文件至文本框或者选择文件", 50);// fileFilePath.setBackground(Color.GRAY);fileFilePath.setForeground(Color.GRAY);fileButton = new JButton("...");// xmlFilePath = new JTextField("选择Xml目标文件", 50);covertButton = new JButton("开始转换");jFileChooser = new JFileChooser();//Container container = getContentPane(); // container.add(jPanel);//Box excelLabelBox = Box.createHorizontalBox();// 创建一个水平箱容器container.add(excelLabelBox, BorderLayout.NORTH);// 添加到窗体中excelLabelBox.add(Box.createHorizontalStrut(5));// 添加一个5像素宽的水平支柱excelLabelBox.add(excel2XmlR);// 添加到水平箱容器中excelLabelBox.add(xml2ExcelR);excelLabelBox.add(xmind2ExcelR);// container.add(customerBox,BorderLayout.CENTER);// excelLabelBox.add(testcaseVersion);//// excelLabelBox.add(testcaseVerText);//// excelLabelBox.add(testcaseAuthor);//// excelLabelBox.add(testcaseAuthorText);// 创建间隙Box box = Box.createVerticalBox();// 创建一个垂直箱容器// container.add(box, BorderLayout.CENTER);// 添加到窗体中box.add(Box.createVerticalStrut(5));// 添加一个5像素高的垂直支柱,设置组件的垂直距离Box excelbox = Box.createHorizontalBox();// 创建一个垂直箱容器excelbox.add(Box.createHorizontalStrut(1));// 添加一个5像素高的垂直支柱box.add(excelbox);excelbox.add(fileFilePath);excelbox.add(Box.createHorizontalStrut(5));// 添加一个5像素宽的水平支柱excelbox.add(fileButton);box.add(Box.createVerticalStrut(15));// 添加一个5像素高的垂直支柱box.add(Box.createVerticalStrut(15));// 添加一个5像素高的垂直支柱container.add(box, BorderLayout.CENTER);// 添加到窗体中// 为按钮添加监听事件excel2XmlR.addActionListener(this);xml2ExcelR.addActionListener(this);xmind2ExcelR.addActionListener(this);fileButton.addActionListener(this);// testcaseVerText.addActionListener(this);covertButton.addActionListener(this);Image imag = null;try {imag = ImageIO.read(this.getClass().getResource("images/testlink.png"));} catch (IOException e2) {// TODO 自动生成的 catch 块e2.printStackTrace();}container.add(covertButton, BorderLayout.SOUTH);// 添加到窗体中setIconImage(imag);setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);setTitle("TestCase Assistant V1.9");setSize(600, 120);setResizable(false);setVisible(isShowWindow);}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource() == excel2XmlR) {logger.info("excel2XmlR" + "被选中了");xml2ExcelR.setSelected(false);xmind2ExcelR.setSelected(false);}if (e.getSource() == xml2ExcelR) {logger.info("xml2ExcelR" + "被选中了");excel2XmlR.setSelected(false);xmind2ExcelR.setSelected(false);}if (e.getSource() == xmind2ExcelR) {logger.info("xmind2ExcelR" + "被选中了");excel2XmlR.setSelected(false);xml2ExcelR.setSelected(false);}if (e.getSource() == fileButton) {int returnVal = jFileChooser.showOpenDialog(Excel2XMLUI.this);if (returnVal == JFileChooser.APPROVE_OPTION) {File chooserFile = jFileChooser.getSelectedFile();filePath = chooserFile.getAbsolutePath();String inPutFileName = chooserFile.getName();// 输出的xml文件名称fileFilePath.setText(filePath);// 将文件路径填入文本框fileFilePath.setForeground(Color.BLACK);// 设置字体颜色为黑色inputFile = filePath;// 设置输入文件路径// 如果输入文件为.xlsx的Excel文件if (inPutFileName.endsWith("xlsx") || inPutFileName.endsWith("xls") || inPutFileName.endsWith(".xml")|| inPutFileName.endsWith(".xmind")) {if (inPutFileName.endsWith("xlsx")) {outPutFile = new File(inPutFileName.replace("xlsx", "xml"));excel2XmlR.setSelected(true);// 设置Excel2XML为选中xml2ExcelR.setSelected(false);xmind2ExcelR.setSelected(false);Excel2XML.setTestLinkXmlFile(outPutFile);// 设置输出testlink xml文件Excel2XML.setFilePath(inputFile);// 设置Excel文件的路径}// 如果输入文件为.xls的Excel文件if (inPutFileName.endsWith("xls")) {excel2XmlR.setSelected(true);// 设置Excel2XML为选中xml2ExcelR.setSelected(false);xmind2ExcelR.setSelected(false);outPutFile = new File(inPutFileName.replace("xls", "xml"));Excel2XML.setTestLinkXmlFile(outPutFile);// 设置输出testlink xml文件Excel2XML.setFilePath(inputFile);// 设置Excel文件的路径}if (inPutFileName.endsWith(".xml")) {xml2ExcelR.setSelected(true);// 自动选中xml文件单选框excel2XmlR.setSelected(false);xmind2ExcelR.setSelected(false);logger.info("===============输入文件为xml文件==================");// 获得输出Excel文件的名称outPutFile = new File(inPutFileName.replace(".xml", ".xlsx"));inPutXMLFile = chooserFile;// 设置xml文件String excelFile = outPutFile.getAbsolutePath();logger.info("输入xml文件路径为:" + inPutXMLFile.getAbsolutePath());// XML2Excel.inPutXMLFile = inputFile;XML2Excel.setXmlFile(inPutXMLFile);XML2Excel.setExcelFile(excelFile);}if (inPutFileName.endsWith(".xmind")) {xmind2ExcelR.setSelected(true);// 设置xmind为选中状态xml2ExcelR.setSelected(false);excel2XmlR.setSelected(false);logger.info("===============输入文件为xmind文件==================");outPutFile = new File(inPutFileName.replace(".xmind", ".xlsx"));inPutXmindFile = chooserFile;// 设置选中的xmind文件logger.info("----------xmindFile----------------" + chooserFile.getName());// Xmind2Excel.setXmindFilePath(xmindFile.getAbsolutePath());Xmind2Excel4SF.setXmindFile(inPutXmindFile);Date date = new Date();SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyyMMddHHmmss");String timestamp = dateFormatGmt.format(date);xmindExcelFile = inPutXmindFile.getName().replaceAll(".xmind", "") + "xmind2Excel" + timestamp+ ".xlsx";// xmind转换后的Excel用例文件logger.info("----------转换后的文件名称为----------------" + xmindExcelFile);Xmind2Excel4SF.setExcelFilePath(xmindExcelFile);}}logger.info("---------------------输出文件名称为--------------" + outPutFile.getName());}}if (e.getSource() == covertButton) {inputFile = Excel2XML.getFilePath();// 获取Excel用例文件路径if (excel2XmlR.isSelected()) {Excel2XML.parseTestCase(inputFile, true);outPutFile = Excel2XML.getTestLinkXmlFile();// 获取输出xml文件路径Excel2XML.excel2Xml(outPutFile);String outPutFileFolder = outPutFile.getAbsolutePath();ExcelUtil.setFileFordler(outPutFileFolder);// logger.info(outPutFile.getPath());logger.info(outPutFile.getParentFile());logger.info(outPutFile.getAbsolutePath().replace(outPutFile.getPath(), ""));}if (xml2ExcelR.isSelected()) {try {// 将xml文件转换为ExcelXML2Excel.xml2Excel();String outPutFileFolder = XML2Excel.getExcelFile();ExcelUtil.setFileFordler(outPutFileFolder);// 设置输出文件路径logger.info("xmind 生成的Excel 文件路径为:" + outPutFileFolder);} catch (Exception e1) {new ExceptionDialog(this, e1.getMessage(), "出错了", true);e1.printStackTrace();}}// String caseVersion=testcaseVerText.getText();// logger.info("Excel2XMLUI------------用例版本号为:------------------" +// caseVersion);// String author=testcaseAuthorText.getText();// logger.info("Excel2XMLUI------------用例维护者工号为:------------------" + author);if (xmind2ExcelR.isSelected()) {// if(caseVersion!=""||!caseVersion.isEmpty()) {// Xmind2Excel4SF.setTestcaseVersion(caseVersion);//设置测试用例版本// }//// if(author!=""||!author.isEmpty()) {// Xmind2Excel4SF.setTestcaseAuthor(author);//设置测试用例版本// }// 将xmind文件转换为Exceltry {// Xmind2Excel.xmind2Excel();// String outPutFileFolder = Xmind2Excel.getExcelFilePath();Xmind2Excel4SF.xmind2Excel();String outPutFileFolder = Xmind2Excel4SF.getExcelFilePath();ExcelUtil.setFileFordler(outPutFileFolder);// 设置输出文件路径logger.info("xmind 生成的Excel 文件路径为:" + outPutFileFolder);} catch (FileNotFoundException e1) {new ExceptionDialog(this, e1.getMessage(), "出错了", true);e1.printStackTrace();} catch (DocumentException e1) {new ExceptionDialog(this, e1.getMessage(), "出错了", true);e1.printStackTrace();}}}}@SuppressWarnings("static-access")@Overridepublic void dragEnter(DropTargetDragEvent dtde) {DataFlavor[] dataFlavors = dtde.getCurrentDataFlavors();if (dataFlavors[0].match(DataFlavor.javaFileListFlavor)) {try {Transferable tr = dtde.getTransferable();Object obj = tr.getTransferData(DataFlavor.javaFileListFlavor);List files = (List) obj;// File files= (File) obj;for (int i = 0; i < files.size(); i++) {fileFilePath.setText(files.get(i).getAbsolutePath());fileFilePath.setForeground(Color.BLACK);inPutFileName = files.get(i).getName();filePath = files.get(i).getAbsolutePath();chooserFile = files.get(i);}inputFile = filePath;// 设置输入文件路径// 如果输入文件为.xlsx的Excel文件if (inPutFileName.endsWith("xlsx") || inPutFileName.endsWith("xls") || inPutFileName.endsWith(".xml")|| inPutFileName.endsWith(".xmind")) {if (inPutFileName.endsWith("xlsx")) {excel2XmlR.setSelected(true);// 选中Excel2xml单选框xml2ExcelR.setSelected(false);xmind2ExcelR.setSelected(false);outPutFile = new File(inPutFileName.replace("xlsx", "xml"));Excel2XML.setTestLinkXmlFile(outPutFile);// 设置输出testlink xml文件Excel2XML.setFilePath(inputFile);// 设置Excel文件的路径}// 如果输入文件为.xls的Excel文件if (inPutFileName.endsWith("xls")) {excel2XmlR.setSelected(true);// 选中Excel2xml单选框xml2ExcelR.setSelected(false);xmind2ExcelR.setSelected(false);outPutFile = new File(inPutFileName.replace("xls", "xml"));Excel2XML.setTestLinkXmlFile(outPutFile);// 设置输出testlink xml文件Excel2XML.setFilePath(inputFile);// 设置Excel文件的路径}if (inPutFileName.endsWith(".xml")) {logger.info("===============输入文件为xml文件==================");xml2ExcelR.setSelected(true);// 自动选中xml文件单选框excel2XmlR.setSelected(false);xmind2ExcelR.setSelected(false);// 获得输出Excel文件的名称outPutFile = new File(inPutFileName.replace(".xml", ".xlsx"));inPutXMLFile = chooserFile;// 设置xml文件String excelFile = outPutFile.getAbsolutePath();logger.info("输入xml文件路径为:" + inPutXMLFile.getAbsolutePath());// XML2Excel.inPutXMLFile = inputFile;XML2Excel.setXmlFile(inPutXMLFile);XML2Excel.setExcelFile(excelFile);}if (inPutFileName.endsWith(".xmind")) {logger.info("===============输入文件为xmind文件==================");xmind2ExcelR.setSelected(true);// 设置xmind2Excel为选中状态excel2XmlR.setSelected(false);xml2ExcelR.setSelected(false);inPutXmindFile = chooserFile;logger.info("输入的文件为:" + inPutXmindFile.getName() + " 路径为:" + inPutXmindFile.getAbsolutePath());if (inPutXmindFile != null) {// Xmind2Excel.setXmindFilePath(inPutXmindFile.getAbsolutePath());Date date = new Date();SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyyMMddHHmmss");String timestamp = dateFormatGmt.format(date);logger.info("----------转换后的文件名称为----------------" + xmindExcelFile);Xmind2Excel4SF.setXmindFile(inPutXmindFile);xmindExcelFile = inPutXmindFile.getName().replaceAll(".xmind", "") + "xmind2Excel"+ timestamp + ".xlsx";// xmind转换后的Excel用例文件Xmind2Excel4SF.setExcelFilePath(xmindExcelFile);}}} else {new ExceptionDialog(this, "文件格式不正确!", "文件格式不正确!");}} catch (UnsupportedFlavorException ex) {new ExceptionDialog(this, "出错了!", ex.getMessage());} catch (IOException ex) {new ExceptionDialog(this, "出错了!", ex.getMessage());}}}@Overridepublic void dragOver(DropTargetDragEvent dtde) {// TODO 自动生成的方法存根}@Overridepublic void dropActionChanged(DropTargetDragEvent dtde) {// TODO 自动生成的方法存根}@Overridepublic void dragExit(DropTargetEvent dte) {// TODO 自动生成的方法存根}@Overridepublic void drop(DropTargetDropEvent dtde) {// TODO 自动生成的方法存根}}
提示窗口UI类:
package com.testlink;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class ExceptionDialog extends JDialog implements ActionListener {/*** */private static final long serialVersionUID = 2057111266020066360L;JButton jButton = null;public ExceptionDialog(Frame owner, String title, String label) {super(owner, title);Container container = getContentPane();// 创建一个容器// String label = "生成xml文件完成!";JLabel jLabel = new JLabel(label);jLabel.setHorizontalAlignment(SwingConstants.LEFT);// jButton = new JButton("打开文件");// jButton.setBounds(0, 0, 20, 10);// jButton.setLayout(new FlowLayout());// 注册按钮监听// jButton.addActionListener(this);// container.setLayout(new FlowLayout(1,10,10));JPanel jPanel = new JPanel(new FlowLayout(2, 20, 20));jPanel.add(jLabel);// jPanel.add(jButton);// container.setLayout(new GridLayout(1, 2, 20, 20));container.add(jPanel);// container.add(jButton);setBounds(120, 120, 300, 150);setResizable(false);// 设置不能调整窗口大小setVisible(true);}public ExceptionDialog(Frame owner, String excepetionLabel, String title, boolean isVeiw) {super(owner, title);Container container = getContentPane();// 创建一个容器String label = title;JLabel jLabel = new JLabel(label);jButton = new JButton("打开文件");jButton.setBounds(0, 0, 20, 10);// 注册按钮监听jButton.addActionListener(this);// 注册按钮监听JTextArea jeArea = new JTextArea(excepetionLabel, 10, 30);JScrollPane jScrollPane = new JScrollPane(jeArea);JPanel jPanel = new JPanel();jPanel.add(jLabel);jPanel.add(jButton);container.add(jPanel);container.add(jScrollPane);container.setLayout(new FlowLayout());// container.add(jButton);setSize(400, 300);setResizable(false);// 设置不能调整窗口大小setVisible(isVeiw);}@Overridepublic void actionPerformed(ActionEvent e) {// 打开xml文件目录if (e.getSource() == jButton) {ExcelUtil.open_directory(ExcelUtil.getFileFordler());System.exit(0);// 退出}}}
Excel工具类:
package com.testlink;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 org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ExcelUtil {private static String fileOutPutFordler;public static String getFileFordler() {return fileOutPutFordler;}public static void setFileFordler(String fileFordler) {fileOutPutFordler = fileFordler;}public ExcelUtil() {}// 读取excel/*** * @param filePath* 读取文件的路径* @return*/@SuppressWarnings("resource")public static Workbook readExcel(String filePath) {Workbook wb = null;if (filePath == null) {return null;}String extString = filePath.substring(filePath.lastIndexOf("."));InputStream is = null;try {is = new FileInputStream(filePath);if (".xls".equals(extString)) {return wb = new HSSFWorkbook(is);} else if (".xlsx".equals(extString)) {return wb = new XSSFWorkbook(is);} else {return wb = null;}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return wb;}/*** 创建Excel文件* * @return Excel对象* @throws IOException*/public static ExcelUtil createExcel(String fileName) {Workbook wb = null;if (fileName.endsWith(".xls")) {wb = new HSSFWorkbook();wb.createSheet();}if (fileName.endsWith(".xlsx")) {wb = new XSSFWorkbook();wb.createSheet();}try {OutputStream fileOut = new FileOutputStream(fileName);wb.write(fileOut);} catch (FileNotFoundException e) {// TODO 自动生成的 catch 块e.printStackTrace();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}return new ExcelUtil();}/**** 打开文件、文件夹* * @param folder* : directory*/public static void open_directory(String folder) {File file = new File(folder);if (!file.exists()) {return;}Runtime runtime = null;try {runtime = Runtime.getRuntime();runtime.exec("cmd /c start explorer " + folder);} catch (IOException ex) {ex.printStackTrace();} finally {if (null != runtime) {runtime.runFinalization();}}}}
文件工具类:
package com.testlink;import org.apache.commons.io.FileUtils;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;/*** 文件工具类* * @author MavenLea**/
public class FileUtil implements TestCaseLog {// static File xmindFile = new File("template.xmind");// 输入的xmind文件/*** * @param xmindFile* xmind文件* @return xmind zip文件*/public static File getXmindFile2Zip(File xmindFile) {File file = new File("Extract\\" + xmindFile.getName());if (!file.exists()) {file.mkdir();}// 将文件复制一份copyFileUsingApacheCommonsIO(xmindFile, file);xmindFile = file;logger.info("使用备份xmind文件转换,路径为" + xmindFile.getAbsolutePath());String xmindFileDest = xmindFile.getAbsolutePath().replaceAll(".xmind", ".zip");// 将xmind文件转换为zip文件logger.info("xmindFileDest:" + xmindFileDest);File xmindZipFile = new File(xmindFileDest);xmindFile.renameTo(xmindZipFile);logger.info("转换后的名称为:" + xmindZipFile.getName());return xmindZipFile;}/*** 文件复制* * @param source* 源文件* @param dest* 目标文件*/private static void copyFileUsingApacheCommonsIO(File source, File dest) {try {FileUtils.copyFile(source, dest);} catch (IOException e) {e.printStackTrace();}}// public void setXmindFile(File xmindFile) {// this.xmindFile = xmindFile;// }/*** 解压到指定目录并取得xmind 的content.xml文件* * @return*/public static File unZipFiles(String zipPath, String descDir) throws IOException {logger.info("获取解压文件夹descDir文件的路径为: " + descDir);// setDescDir(descDir);unZipFiles(new File(zipPath), descDir);File xmindContentFile = new File(descDir + "/content.xml");logger.info("获取xmind的content.xml文件的路径为: " + xmindContentFile.getAbsolutePath());return xmindContentFile;}/*** 解压文件到指定目录*/@SuppressWarnings("rawtypes")public static void unZipFiles(File zipFile, String descDir) throws IOException {File pathFile = new File(descDir);if (!pathFile.exists()) {pathFile.mkdirs();}// 解决zip文件中有中文目录或者中文文件ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {ZipEntry entry = (ZipEntry) entries.nextElement();String zipEntryName = entry.getName();InputStream in = zip.getInputStream(entry);String outPath = (descDir + "/" + zipEntryName);// 判断路径是否存在,不存在则创建文件路径File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));if (!file.exists()) {file.mkdirs();}// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压if (new File(outPath).isDirectory()) {continue;}// 输出文件路径信息logger.info(outPath);OutputStream out = new FileOutputStream(outPath);byte[] buf1 = new byte[1024];int len;while ((len = in.read(buf1)) > 0) {out.write(buf1, 0, len);}in.close();out.close();}logger.info("******************解压完毕********************");}// public static void main(String[] args) throws IOException {// /**// * 解压文件// */// // File zipFile=new File("template.zip");//// File xmindZipFile=getXmindFile2Zip(xmindFile);// File zipFile = xmindZipFile;// String descDir = "template";// String path=descDir;// String zipPath=zipFile.getAbsolutePath();//// unZipFiles(zipPath, path);//// //unZipFiles(zipFile, descDir);//// }}
Log类:
package com.testlink;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;public interface TestCaseLog {Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);}
用例模板类:
package com.testlink;public class TestCaseTemplate {public static final int TESTCASENAME=0;//用例名称public static final int PREDICOTON=1;//前提条件public static final int ACTIONS=2;//操作步骤public static final int RESULTS=3;//期望结果public static final int PRIORITY=4;//优先级public static final int MODULE=5;//所属模块public static final int VERSION=6;//版本号public static final int TESTCASETYPE=7;//用例类型public static final int RELATEDREQUIMENT=8;//关联需求public static final int ISAUTOMOTION=9;//关联需求public static final int AUTHOR=10;//关联需求}
Excel转XML类:
package com.testlink;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;import com.testlink.ui.TestAssistantUI4SF;
import com.testlink.ui.ExceptionDialog;
import com.testlink.ui.TestCaseLog;
import com.util.ExcelUtil;public class Excel2XML implements TestCaseLog {public Excel2XML() {}static int stepNum = 1;// 用例步骤//static String excelFilePath;static File testLinkXmlFile;public static File getTestLinkXmlFile() {return testLinkXmlFile;}public static void setTestLinkXmlFile(File testLinkXmlFile) {Excel2XML.testLinkXmlFile = testLinkXmlFile;}public static String getFilePath() {return excelFilePath;}public static void setFilePath(String excelFilePath) {Excel2XML.excelFilePath = excelFilePath;}/*** 写出testlink xml文件*/public static void excel2Xml(File testLinkXmlFile) {try {OutputFormat format = OutputFormat.createPrettyPrint();format.setEncoding("UTF-8");// FileWriter out = new FileWriter(testLinkXmlFile);//// 使用FileWriter会出现打包后乱码,改用FileOutputStreamFileOutputStream out = new FileOutputStream(testLinkXmlFile);Document document = parseTestCase(excelFilePath, false);XMLWriter writer2File;writer2File = new XMLWriter(out, format);writer2File.write(document);out.close();// 美化文档格式输出到System.outXMLWriter writer;writer = new XMLWriter(System.out, format);writer.write(document);} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}/*** * @param filePath* excel测试用例路径* @return xml Document对象*/@SuppressWarnings("deprecation")public static Document parseTestCase(String filePath, boolean isView) {// DataFormatter formatter = new DataFormatter();Workbook workbook = ExcelUtil.readExcel(filePath);// 读取Excel文件Sheet caseSheet = workbook.getSheetAt(0);// 获取解析用例的表格Document document = DocumentHelper.createDocument();// 设置xml根节点属性Element root = document.addElement("testsuite");root.addAttribute("name", "");// 添加name属性// 设置xml头信息Element nodeOrder = root.addElement("node_order");nodeOrder.addCDATA("");Element details = root.addElement("details");details.addCDATA("");logger.info("最大行数为:" + caseSheet.getLastRowNum());Element testsuiteChildNodes = null;Element testCase = null;Element steps = null;// 从第二行开始读取,遍历整个用例表StringBuffer buf = new StringBuffer("");for (int pathRow = 1; pathRow <= caseSheet.getLastRowNum(); pathRow++) {Element parent = root; // 将parent设置为根目录logger.info("==========================当前为第" + pathRow + "次循环===========================================");Row currentRow = caseSheet.getRow(pathRow);Cell testsuiteCell = currentRow.getCell(0);// 获取案例路径logger.info("当前为:" + currentRow.getRowNum() + "行");// 获取testsuite的值try {if (testsuiteCell != null) {if (testsuiteCell.getCellType() == Cell.CELL_TYPE_STRING) {String path_str = testsuiteCell.getStringCellValue();logger.info(testsuiteCell.getRichStringCellValue().getString());// 如果用例包含多层路径if (path_str.contains("/")) {String[] path = path_str.split("/");for (String str : path) {logger.info("str====================" + str);String dirName = str;testsuiteChildNodes = parent.addElement("testsuite").addAttribute("name", dirName);testsuiteChildNodes.addElement("node_order").addCDATA("");testsuiteChildNodes.addElement("details").addCDATA("");parent = testsuiteChildNodes;// 替换父节点}} else {// 不包含多层路径testsuiteChildNodes = parent.addElement("testsuite").addAttribute("name", path_str);testsuiteChildNodes.addElement("node_order").addCDATA("");testsuiteChildNodes.addElement("details").addCDATA("");parent = testsuiteChildNodes;// 替换父节点}}}} catch (Exception e) {// TODO 自动生成的 catch 块e.printStackTrace();logger.error(e.getMessage());}// 获取用例名称Cell caseCell = currentRow.getCell(1);// 获取用例名称if (caseCell != null) {logger.info("第" + pathRow + "次循环========================================用例名称为:"+ caseCell.getStringCellValue());}Cell summaryCell = currentRow.getCell(2);// 获取摘要if (summaryCell != null) {logger.info("第" + pathRow + "次循环========================================摘要名称为:"+ summaryCell.getStringCellValue());}Cell stepCell = currentRow.getCell(5);// 获取步骤if (stepCell != null) {logger.info("步骤为:========================" + stepCell.getStringCellValue());}// 设置预期结果Cell expectedresultsCell = currentRow.getCell(6);if (expectedresultsCell != null) {logger.info("期望为:========================" + expectedresultsCell.getStringCellValue());}String caseName = null;// 用例名称if (caseCell != null) {if (caseCell.getCellType() == Cell.CELL_TYPE_STRING && caseCell.getCellType() != Cell.CELL_TYPE_BLANK) {stepNum = 1;if (caseCell.getStringCellValue() != null) {caseName = caseCell.getStringCellValue();testCase = testsuiteChildNodes.addElement("testcase").addAttribute("name", caseName);testCase.addElement("node_order").addCDATA("");String summaryName = null;if (summaryCell != null && summaryCell.getCellType() == Cell.CELL_TYPE_STRING&& summaryCell.getCellType() != Cell.CELL_TYPE_BLANK) {summaryName = summaryCell.getStringCellValue();testCase.addElement("summary").addCDATA("" + summaryName + "
");}// 获取优先级Cell importanceCell = currentRow.getCell(3);// 获取优先级String importance = null;if (importanceCell.getCellType() == Cell.CELL_TYPE_STRING&& importanceCell.getCellType() != Cell.CELL_TYPE_BLANK) {importance = importanceCell.getStringCellValue();testCase.addElement("importance").addCDATA(importance);}// 获取前提,前提不为空Cell preconditionsCell = currentRow.getCell(4);// 获取前提String preconditions = null;if (preconditionsCell != null) {int preconditionsCellType = preconditionsCell.getCellType();if (preconditionsCellType == Cell.CELL_TYPE_STRING&& preconditionsCellType != Cell.CELL_TYPE_BLANK) {preconditions = preconditionsCell.getStringCellValue();// 如果有多个操作步骤if (preconditions != null) {if (preconditions.startsWith("1、")) {preconditions = splitMuiltyStep(preconditions);logger.info("多个前提条件******************************************多个前提条件" + preconditions);testCase.addElement("preconditions").addCDATA("" + preconditions + "
");} else {logger.info("没有多个前提条件******************************************没有多个前提条件" + preconditions);testCase.addElement("preconditions").addCDATA("" + preconditions + "
");}}}// 前提为空的 情况if (preconditionsCell.getCellType() == Cell.CELL_TYPE_BLANK) {testCase.addElement("preconditions").addCDATA("");}}testCase.addElement("status").addText("7");//用例状态:草稿、准备评审...最终稿// 添加步骤标签steps = testCase.addElement("steps");}}}String step = null;if (stepCell != null) {if (stepCell.getCellType() == Cell.CELL_TYPE_STRING) {// 获取步骤中的描述step = stepCell.getStringCellValue();logger.info("===================================步骤为:" + step);// 如果有多个操作步骤step = step.replaceAll("\n", "");// 替换所有的换行符}if (caseName == null&&stepCell != null) {// && caseCell.getCellType() == Cell.CELL_TYPE_BLANKstepNum++;logger.info("存在多个步骤================================stepNum的值为:" + stepNum);}else {logger.info("不存在多个步骤================================stepNum的值为:" + stepNum);}}String expectedresults = null;if(expectedresultsCell!=null) {if (expectedresultsCell.getCellType() == Cell.CELL_TYPE_STRING) {expectedresults = expectedresultsCell.getStringCellValue();// // 获取步骤中的描述Element actionStep = steps.addElement("step");// // 设置步骤顺序actionStep.addElement("step_number").addCDATA(Integer.toString(stepNum));logger.info("*************************************" + stepNum);logger.info("当前用例:<" + caseName + "> 步骤数为" + stepNum);// 设置步骤logger.info("=============================================操作步骤为:" + step);// 如果有多个操作步骤if (step != null) {if (HasDigit(step) && step.startsWith("1、")) {step = splitMuiltyStep(step);logger.info("多步操作******************************************多步操作" + step);actionStep.addElement("actions").addCDATA(step);} else {actionStep.addElement("actions").addCDATA("" + step + "
");}}if (step == null) {//buf.append("第" + pathRow + "行操作步骤为空,请确认!" + "\n");}// 设置预期结果logger.info("期望结果为:" + expectedresults);// 如果期望结果有多个expectedresults = expectedresults.replaceAll("\\n", "");logger.info("期望结果" + expectedresults);if (expectedresults != null) {
// boolean expectedResultsHasDigit=false;
// expectedResultsHasDigit=HasDigit(expectedresults);boolean isStartOne=false;isStartOne=expectedresults.startsWith("1、")||expectedresults.startsWith("1.");if (isStartOne) {expectedresults = splitMuiltyStep(expectedresults);logger.info(expectedresults);logger.info("多步操作******************************************多步操作" + expectedresults);actionStep.addElement("expectedresults").addCDATA(expectedresults);} else {logger.info("没有多个期望");actionStep.addElement("expectedresults").addCDATA("" + expectedresults + "
");}}}}if (pathRow == caseSheet.getLastRowNum()) {new ExceptionDialog(new TestAssistantUI4SF(false), buf.toString(), "生成xml文件完成", isView);}}return document;}/*** 分割多步骤,多期望的用例* * @param stepStr* 多步操作的字符串* @return 解析后的多步操作*/public static String splitMuiltyStep(String stepStr) {String regex = "\\d+、";String newStep = "";String arry[] = stepStr.split(regex);for (int i = 0; i < arry.length; i++) {if (i != 0) {logger.info(arry[0]);logger.info("" + i + "、" + arry[i] + "
");newStep += "" + i + "、" + arry[i] + "
";}}return newStep;}/*** 判断字符串中是否存在数字* * @param content* @return*/public static boolean HasDigit(String content) {boolean flag = false;Pattern p = Pattern.compile(".*\\d+.*");Matcher m = p.matcher(content);if (m.matches()) {flag = true;}return flag;}}
Xmind转Excel类:
package com.testlink;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;public class Xmind2Excel4SF implements TestCaseLog {private static String xmindFilePath;static CellStyle cellStyle = null;public static String getTestcaseVersion() {return testcaseVersion;}public static void setTestcaseVersion(String testcaseVersion) {Xmind2Excel4SF.testcaseVersion = testcaseVersion;}private static String testcaseVersion;// 测试用例版本private static String testcaseAuthor;// 用例维护者工号private static String testcaseType;// 用例版本号public static String getTestcaseAuthor() {return testcaseAuthor;}public static void setTestcaseAuthor(String testcaseAuthor) {Xmind2Excel4SF.testcaseAuthor = testcaseAuthor;}public static String getXmindFilePath() {return xmindFilePath;}public static void setXmindFilePath(String xmindFilePath) {Xmind2Excel4SF.xmindFilePath = xmindFilePath;}/*** 获取文件的document对象,然后获取对应的根节点* * @author MavenLea*/SAXReader sax = new SAXReader();// 创建一个SAXReader对象// static String xmindFiltPath="template.xmind";//xmind文件路径// 测试// static File xmindFile = new File("始发地航空站点0620版本.xmind");// xmind 原始文件static File xmindFile;// xmind 原始文件public static File getXmindFile() {return xmindFile;}//public static void setXmindFile(File xmindFile) {Xmind2Excel4SF.xmindFile = xmindFile;}// static Element parentNode = null;static int testcaseRowNum = 1;// 测试用例起始行// static String testcasePath1 = "";static String currentParentSuiteName = null;// 当前测试组件的名称public static String getExcelFilePath() {return excelFilePath;}public static void setExcelFilePath(String excelFilePath) {Xmind2Excel4SF.excelFilePath = excelFilePath;}static String excelFilePath;// 输出的测试用例文件// static String excelFilePath ="xmind2testcase180606.xlsx";// xmind转换后的Excel用例文件@SuppressWarnings("static-access")static Workbook workbook;static Sheet caseSheet;static Row testcaseRow;// =static String testcaseName = null;// 用例名称static String importance = "";// 用例优先级static String requirement = "";private static Element moduleNode;private static Element requirementNode;// public static void main(String[] args) throws FileNotFoundException,// DocumentException {// xmind2Excel();//// }private static String getTestElments(List e) {// for (Element exceptEl : excepts) {//// except = exceptEl.element("title").getStringValue();// 用例期望// exceptList.add(except);// }int exceptSize = e.size();// 单个操作if (exceptSize == 1) {logger.info("在" + testcaseRow.getRowNum() + "---------------行设置用例期望-----------------------");String s = e.get(0).element("title").getStringValue();return s;}// 多个操作if (exceptSize > 1) {StringBuffer str = new StringBuffer();int i = 1;for (Element mExcept : e) {str.append(i + "、" + mExcept.element("title").getStringValue() + "\n");i++;}logger.info("在" + testcaseRow.getRowNum() + "---------------行设置用例期望-----------------------");return str.toString();}return null;}/*** * @param e* 当前Topics节点* @return 返回当前Topics节点的上一个Topics节点*/public static Element getParentElement(Element e) {return e.getParent().getParent();}/*** 获取文件的document对象,然后获取对应的根节点* * @author MavenLea*/public static void xmind2Excel() throws FileNotFoundException, DocumentException {ExcelUtil.createExcel(excelFilePath);workbook = ExcelUtil.readExcel(excelFilePath);// 读取Excel文件;caseSheet = workbook.getSheetAt(0);// 获取解析用例的表格testcaseRow = caseSheet.createRow(testcaseRowNum);// 默认创建一行logger.info("--------------------");Row testcaseTitle = caseSheet.createRow(0);// 创建表头cellStyle = workbook.createCellStyle(); // 创建一个样式cellStyle.setBorderBottom(BorderStyle.THIN);cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());cellStyle.setBorderLeft(BorderStyle.THIN);cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());cellStyle.setBorderRight(BorderStyle.THIN);cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());cellStyle.setBorderTop(BorderStyle.THIN);cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());Cell testnameCell = testcaseTitle.createCell(TestCaseTemplate.TESTCASENAME);testnameCell.setCellValue("用例名称");testnameCell.setCellStyle(cellStyle);Cell precondictionCell = testcaseTitle.createCell(TestCaseTemplate.PREDICOTON);precondictionCell.setCellValue("前置条件");precondictionCell.setCellStyle(cellStyle);Cell stepCell = testcaseTitle.createCell(TestCaseTemplate.ACTIONS);stepCell.setCellValue("操作步骤");stepCell.setCellStyle(cellStyle);Cell expectCell = testcaseTitle.createCell(TestCaseTemplate.RESULTS);expectCell.setCellValue("预期结果");expectCell.setCellStyle(cellStyle);Cell importanceCell = testcaseTitle.createCell(TestCaseTemplate.PRIORITY);importanceCell.setCellValue("优先级");importanceCell.setCellStyle(cellStyle);Cell testcasesPathCell = testcaseTitle.createCell(TestCaseTemplate.MODULE);testcasesPathCell.setCellValue("所属模块");testcasesPathCell.setCellStyle(cellStyle);Cell testcasesVersionCell = testcaseTitle.createCell(TestCaseTemplate.VERSION);testcasesVersionCell.setCellValue("版本号");testcasesVersionCell.setCellStyle(cellStyle);Cell testcasesTypeCell = testcaseTitle.createCell(TestCaseTemplate.TESTCASETYPE);testcasesTypeCell.setCellValue("用例类型");testcasesTypeCell.setCellStyle(cellStyle);Cell testcasesRelatedRequimentCell = testcaseTitle.createCell(TestCaseTemplate.RELATEDREQUIMENT);testcasesRelatedRequimentCell.setCellValue("关联需求");testcasesRelatedRequimentCell.setCellStyle(cellStyle);Cell testcasesIsAutoCell = testcaseTitle.createCell(TestCaseTemplate.ISAUTOMOTION);testcasesIsAutoCell.setCellValue("是否自动化");testcasesIsAutoCell.setCellStyle(cellStyle);Cell testcasesAuthorCell = testcaseTitle.createCell(TestCaseTemplate.AUTHOR);testcasesAuthorCell.setCellValue("用例维护人");testcasesAuthorCell.setCellStyle(cellStyle);// Cell testSummaryCell = testcaseTitle.createCell(2);// testSummaryCell.setCellValue("操作步骤");// String excelFilePath = xmindFile.getName() + "xmind2testcase.xlsx";OutputStream stream;SAXReader sax = new SAXReader();// 创建一个SAXReader对象// 获取xmindFile// File xmindFile=new File(xmindFile)// 将xmind转换为zip文件logger.info("转换xmind文件为zip...");File xmindZipFile = FileUtil.getXmindFile2Zip(xmindFile);logger.info("获取xmind zip文件路径...");String zipPath = xmindZipFile.getAbsolutePath();logger.info("=================xmind zip文件路径zipPath为====================" + zipPath);String descDir = zipPath.replaceAll(".zip", "");logger.info("=========================xmind zip文件解压目录descDir为============" + descDir);// 解压并 获取xmind content.xml文件File xmlFile = null;try {logger.info("========================获取xmind content.xml文件========================================");xmlFile = FileUtil.unZipFiles(zipPath, descDir);} catch (IOException e) {e.printStackTrace();logger.error(e.getMessage());}Document document = sax.read(xmlFile);// 获取document对象,如果文档无节点,则会抛出Exception提前结束Element root = document.getRootElement();// 获取根节点logger.info("--------------------根节点名称为:" + root.getName());getNodes(root);// 从根节点开始遍历所有节点int rownum = caseSheet.getLastRowNum();Row lastRow = caseSheet.getRow(rownum);caseSheet.removeRow(lastRow);try {stream = new FileOutputStream(excelFilePath);workbook.write(stream);stream.close();} catch (IOException e1) {// TODO 自动生成的 catch 块e1.printStackTrace();logger.error(e1.getMessage());}}/*** 递归查找children节点下的子节点* * @param e*/public static void findChild(Element e) {Element children = e.element("children");Element childrenTp = children.element("topics");List excepts = childrenTp.elements("topic");for (Element exceptEl : excepts) {String except = exceptEl.attributeValue("title");// 用例期望logger.info("children递归为:" + except);findChild(exceptEl);}}public static String xmindParse(Element node) {logger.info("#################################当前行数为:" + testcaseRowNum);testcaseVersion = getTestcaseVersion();// 用例版本testcaseAuthor = getTestcaseAuthor();// 用例作者String nodeName = node.getName();List testsuiteTopic = new ArrayList<>();// Cell testcaseSummaryCell = testcaseRow.createCell(2);// 用例名称// 获取用例的版本号、维护人、用例类型if (nodeName.equals("sheet")) {List testcaseProperty = null;Element firstElement = node.element("topic");logger.info("第一个Topic元素的ID为:" + firstElement.attribute("id").getStringValue());Element firstTopicNotes = firstElement.element("notes");if (firstTopicNotes != null) {Element html = firstTopicNotes.element("html");testcaseProperty = html.elements();testcaseVersion = testcaseProperty.get(0).getStringValue().split(":")[1];testcaseAuthor = testcaseProperty.get(1).getStringValue().split(":")[1];testcaseType = testcaseProperty.get(2).getStringValue().split(":")[1];logger.info("*****************==================获取的用例版本号为:" + testcaseVersion + " 维护人为:"+ testcaseAuthor + " 用例类型为:" + testcaseType + "*****************");}}// 分支主题String topicID = null;if (nodeName.equals("topics") && node.attributeValue("type").equals("attached")) {topicID = node.element("topic").attributeValue("id");logger.info("*****************==================获取的节点名称为:" + nodeName + " topicID为:" + topicID+ "*****************");List topicList = node.elements("topic");// 获取分支节点for (Element e : topicList) {if (e.getName().equals("topic")) {// 获取主题图标Element marker = e.element("marker-refs");if (marker != null) {Element markerRef = marker.element("marker-ref");String markerIcon = markerRef.attributeValue("marker-id");logger.info("a==================主题引用的图标为:" + markerIcon);// 测试用例,获取测试用例的名称String topicName = e.element("title").getStringValue();// 获取用例前提及描述Element notes = e.element("notes");// 获取用例备注// 优先级标记表示测试用例if (markerIcon.startsWith("priority")) {testcaseRowNum++;// 取得优先级数字String suffix = markerIcon.replaceAll("priority-", "");logger.info("suf=-----------------" + suffix);testcaseName = topicName;if (notes != null) {String prediction = notes.element("plain").getStringValue();// 前提Cell testcasePreconditionsCell = testcaseRow.createCell(TestCaseTemplate.PREDICOTON);testcasePreconditionsCell.setCellStyle(cellStyle);testcasePreconditionsCell.setCellValue(prediction);}// 判断用例优先级switch (suffix) {case "1":importance = "高";break;case "2":importance = "中";break;case "3":importance = "低";break;}logger.info("当前节点为测试用例,用例名称为:" + testcaseName + " 优先级为:" + importance);// 测试组件requirementNode = getParentElement(node);// 获取当前节点的父节点,topic节点的上级父节点即关联需求节点List testSuitePathList = new ArrayList();String currentestsuiteName = null;// 测试用例名称Element moduleMarker = null;try {moduleNode = getParentElement(requirementNode).getParent();// 更新节点位置到模块位置moduleMarker = moduleNode.element("marker-refs");} catch (Exception e1) {// TODO 自动生成的 catch 块e1.printStackTrace();logger.info(e1.getMessage());}String testsuiteMarkerIconID = null;if (moduleMarker != null) {Element testsuiteMarkerRef = moduleMarker.element("marker-ref");testsuiteMarkerIconID = testsuiteMarkerRef.attributeValue("marker-id");logger.info("测试节点==================主题引用的图标为:" + markerIcon);logger.info("测试模块==================主题引用的marker-id为:" + testsuiteMarkerIconID);String testsuiteTopicName = moduleNode.element("title").getStringValue();// // 旗帜标记表示测试组件//if (testsuiteMarkerIconID.startsWith("flag")) {currentestsuiteName = testsuiteTopicName;logger.info("当前节点为测试组件,名称为:" + testsuiteTopicName);testsuiteTopic.add(currentestsuiteName);logger.info("进入while循环前节点的名称为:" + moduleNode.getName() + " topic值为:"+ testsuiteTopicName);// topic节点的type属性String nodeParentTypeValue = null;nodeParentTypeValue = moduleNode.getParent().attributeValue("type");// 第一个topic节点具有的属性String rootTp = null;if (nodeParentTypeValue != null) {while (nodeParentTypeValue.equals("attached")) {rootTp = moduleNode.getParent().getName();// sheet节点boolean isRootElement = false;isRootElement = moduleNode.isRootElement();if (!isRootElement && rootTp != "sheet") {// 获取当前节点的父节点,topic节点的上级父节点for (int i = 0; i < 3; i++) {moduleNode = moduleNode.getParent();}}// 节点不为空并且包含图标if (moduleNode != null && moduleNode.element("marker-refs") != null) {logger.info("-----节点的名称为--------" + node.getName());currentParentSuiteName = moduleNode.element("title").getStringValue();logger.info("----------------父组件的名称为:" + currentParentSuiteName);} else {break;}testSuitePathList.add(currentParentSuiteName);}}for (String testsuite : testSuitePathList) {logger.info("***********遍历测试组件路径********************" + testsuite);}}StringBuffer stringBuffer = new StringBuffer();Collections.reverse(testSuitePathList);// 获得用例路径for (String suiteName : testSuitePathList) {stringBuffer.append(suiteName + "->");}String testcaseFullPath = stringBuffer + currentestsuiteName;logger.info("用例完整路径为:" + testcaseFullPath);logger.info("在" + testcaseRow.getRowNum()+ "-----------------行设置用例路径-----------------------");Cell testcasePathCell = testcaseRow.createCell(TestCaseTemplate.MODULE);// 用例路径testcasePathCell.setCellStyle(cellStyle);testcasePathCell.setCellValue(testcaseFullPath);logger.info("在" + testcaseRow.getRowNum()+ "-----------------行设置用例名称-----------------------");Cell testcaseNameCell = testcaseRow.createCell(TestCaseTemplate.TESTCASENAME);// 用例名称testcaseNameCell.setCellStyle(cellStyle);testcaseNameCell.setCellValue(testcaseName);logger.info("在" + testcaseRow.getRowNum()+ "-----------------行设置用例优先级-----------------------");Cell testcaseimportanceCell = testcaseRow.createCell(TestCaseTemplate.PRIORITY);// 优先级testcaseimportanceCell.setCellStyle(cellStyle);testcaseimportanceCell.setCellValue(importance);logger.info("用例路径为: " + testcaseFullPath + " 用例名称为:" + testcaseName + " 用例优先级为:"+ importance);Element children = e.element("children");// 获取用例步骤Element stepTp = children.element("topics");logger.info("stepTp的名称为:" + stepTp.getName());List steps = stepTp.elements("topic");// List results=// int stepSize = steps.size();String actions = getTestElments(steps);Cell testcaseActionsCell = testcaseRow.createCell(TestCaseTemplate.ACTIONS);// 创建测试步骤单元格logger.info("=================当前行号testcaseRow为:================" + testcaseRow.getRowNum());logger.info("-------------用例的行数为testcaseRowNum:--------------" + testcaseRowNum);// String action = stepEl.element("title").getStringValue();// 用例步骤logger.info("在" + testcaseRow.getRowNum()+ "---------------行设置用例步骤-----------------------");logger.info("用例步骤为:" + actions);testcaseActionsCell.setCellValue(actions);// 写入测试步骤testcaseActionsCell.setCellStyle(cellStyle);Cell testcaseExpectedresultsCell = testcaseRow.createCell(TestCaseTemplate.RESULTS);// 创建测试期望单元格String testExceptions = null;// 测试期望for (Element stepEl : steps) {Element exceptChild = stepEl.element("children");Element exceptTp = null;if (exceptChild != null) {exceptTp = exceptChild.element("topics");}List excepts = exceptTp.elements("topic");String except = null;List exceptList = new ArrayList<>();for (Element exceptEl : excepts) {except = exceptEl.element("title").getStringValue();// 用例期望exceptList.add(except);}if (getTestElments(excepts) != null) {testExceptions = getTestElments(excepts);}}logger.info("=============用例步骤期望为:======================" + "\n" + testExceptions);try {// CellStyle cellStyle = workbook.createCellStyle();cellStyle.setWrapText(true);testcaseExpectedresultsCell.setCellStyle(cellStyle);testcaseExpectedresultsCell.setCellValue(testExceptions);} catch (Exception e1) {// TODO 自动生成的 catch 块e1.printStackTrace();}node = e.getParent();// 将node的值还原}Cell testcaseVersionCell = testcaseRow.createCell(TestCaseTemplate.VERSION);// 创建测试版本号logger.info("用例的版本号为=-----------------" + testcaseVersion);testcaseVersionCell.setCellStyle(cellStyle);testcaseVersionCell.setCellValue(testcaseVersion);Cell testcaseTypeCell = testcaseRow.createCell(TestCaseTemplate.TESTCASETYPE);// 创建测试用例类型单元格testcaseTypeCell.setCellStyle(cellStyle);testcaseTypeCell.setCellValue(testcaseType);// 需求引用Element requirementMarkerRefs = requirementNode.element("marker-refs");logger.info("需求节点为=-----------------" + requirementNode.getName()+ requirementNode.attributeValue("id"));Element requirementMarkerRef = requirementMarkerRefs.element("marker-ref");String requirementMarkerIcon = requirementMarkerRef.attributeValue("marker-id");// // 判断用例关联的需求星型标记if (requirementMarkerIcon.startsWith("star")) {// 获取需求名称requirement = requirementNode.elementText("title");logger.info("需求为=-----------------" + requirement);Cell testcaseRelatedRequimentCell = testcaseRow.createCell(TestCaseTemplate.RELATEDREQUIMENT);testcaseRelatedRequimentCell.setCellStyle(cellStyle);testcaseRelatedRequimentCell.setCellValue(requirement);}Cell testcaseAutoCell = testcaseRow.createCell(TestCaseTemplate.ISAUTOMOTION);// 创建测试用例类型单元格testcaseAutoCell.setCellStyle(cellStyle);testcaseAutoCell.setCellValue("否");Cell testcaseAuthorCell = testcaseRow.createCell(TestCaseTemplate.AUTHOR);// 创建测试用例类型单元格testcaseAuthorCell.setCellStyle(cellStyle);testcaseAuthorCell.setCellValue(testcaseAuthor);testcaseRow = caseSheet.createRow(testcaseRowNum);// 创建新用例行}}}}}logger.info("*****************==================获取的节点名称为:" + nodeName + "topicID为:" + topicID+ "*****************");logger.info("#################################当前行数为:" + testcaseRowNum);return nodeName;}/*** * @param node* 递归的节点* @throws FileNotFoundException*/public static void getNodes(Element node) throws FileNotFoundException {// 当前节点的名称、文本内容和属性String nodeName = node.getName();String nodeContent = node.getTextTrim();logger.info("当前节点名称:" + nodeName);// 当前节点名称logger.info("当前节点的内容:" + nodeContent);// 当前节点内容if (node != null) {xmindParse(node);}if (nodeContent.equals("画布 1")) {new ExceptionDialog(null, "", "xmind文件转换完毕", true);}// 递归遍历当前节点所有的子节点List listElement = node.elements();// 所有一级子节点的listfor (Element e : listElement) {// 遍历所有一级子节点getNodes(e);// 递归}}}
XML2Excel 类:
package com.testlink;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;public class XML2Excel implements TestCaseLog {/*** 获取文件的document对象,然后获取对应的根节点 ** @author MavenLea*/private static SAXReader sax = new SAXReader();// 创建一个SAXReader对象private static File xmlFile;// xml文件private static String excelFile;// Excel文件public File getXmlFile() {return xmlFile;}public static void setXmlFile(File xmlFile) {XML2Excel.xmlFile = xmlFile;}public static String getExcelFile() {return excelFile;}public static void setExcelFile(String excelFile) {XML2Excel.excelFile = excelFile;}static Element parentNode = null;// 父节点static int testcaseRowNum = 1;// 测试用例行数private static Workbook workbook;// workbook = ExcelUtil.readExcel(excelFilePath);// 读取Excel文件private static Sheet caseSheet;// 获取解析用例的表格private static OutputStream stream;private static Row testcaseRow = null;// 用例行号static String rootName;// //测试用public static void main(String[] args) {try {xml2Excel();} catch (Exception e) {// TODO 自动生成的 catch 块e.printStackTrace();}}/*** ** @param inPutxmlFile 输入的xml文件* @param outPutExcelFile 输出的Excel文件* @throws Exception*/@SuppressWarnings("static-access")public static void xml2Excel() throws Exception {ExcelUtil.createExcel(excelFile);workbook = ExcelUtil.readExcel(excelFile);caseSheet = workbook.getSheetAt(0);// 根据指定的路径创建file对象sax.setEncoding("UTF-8");Document document = sax.read(xmlFile);// 获取document对象,如果文档无节点,则会抛出Exception提前结束Element root = document.getRootElement();// 获取根节点logger.info("----------------------根节点名称为:---------------------" + root.attributeValue("name"));List allChildList = root.elements();int rootEl = allChildList.size();for (Element e : allChildList) {if (e.getName().equals("testsuite")) {rootEl--;}// logger.info("-----------------遍历后节点总数为------------------------"+rootEl);if (rootEl == 2) {new ExceptionDialog(null, "", "xml转Excel完成", true);}}getNodes(root);// 从根节点开始遍历所有节点try {stream = new FileOutputStream(excelFile);workbook.write(stream);stream.close();} catch (IOException e1) {e1.printStackTrace();}}/*** 从指定节点开始,递归遍历所有子节点 ** @param rootName 根节点名称 * @throws FileNotFoundException */public static void getNodes(Element node) throws FileNotFoundException {logger.info("--------------------");Row testcaseTitle = caseSheet.createRow(0);// 创建表头// 设置单元格样式// CellStyle style = workbook.createCellStyle();// style.setBorderBottom(BorderStyle.THIN);// //style.setBorderBottom(BorderStyle.THIN);// style.setBottomBorderColor(IndexedColors.BLACK.getIndex());// style.setBorderLeft(BorderStyle.THIN);// style.setLeftBorderColor(IndexedColors.BLACK.getIndex());// style.setBorderRight(BorderStyle.THIN);// style.setRightBorderColor(IndexedColors.BLACK.getIndex());// style.setBorderTop(BorderStyle.THIN);// style.setTopBorderColor(IndexedColors.BLACK.getIndex());// style.setWrapText(true);Cell testcasesPathCell = testcaseTitle.createCell(0);testcasesPathCell.setCellValue("测试用例路径");// testcasesPathCell.setCellStyle(style);Cell testnameCell = testcaseTitle.createCell(1);testnameCell.setCellValue("测试用例名称");// testnameCell.setCellStyle(style);Cell testSummaryCell = testcaseTitle.createCell(2);testSummaryCell.setCellValue("测试用例描述");// testSummaryCell.setCellStyle(style);Cell importanceCell = testcaseTitle.createCell(3);importanceCell.setCellValue("优先级");// importanceCell.setCellStyle(style);Cell precondictionCell = testcaseTitle.createCell(4);precondictionCell.setCellValue("前提");// precondictionCell.setCellStyle(style);Cell stepCell = testcaseTitle.createCell(5);stepCell.setCellValue("步骤");// stepCell.setCellStyle(style);Cell expectCell = testcaseTitle.createCell(6);expectCell.setCellValue("期望结果");// expectCell.setCellStyle(style);// 当前节点的名称、文本内容和属性String nodeName = node.getName();String nodeContent = node.getTextTrim();logger.info("当前节点名称:" + nodeName);// 当前节点名称logger.info("当前节点的内容:" + nodeContent);// 当前节点内容// testcaseRow=caseSheet.createRow(testcaseRowNum);if (node.isRootElement()) {rootName = node.attributeValue("name");}// testsuite非根节点if (nodeName.equals("testsuite") && node.element("testcase") != null && !node.isRootElement()) {// 非根节点且包含测试用例// 创建测试用例路径单元格// 测试用例路径logger.info("非多步骤创建第" + testcaseRowNum + "行");// cell.setCellStyle(style);testcaseRow = caseSheet.createRow(testcaseRowNum);Cell testcasePathCell = testcaseRow.createCell(0);String currentSuiteName = null;// testcasePathCell.setCellStyle(style);logger.info("===================节点名称为:" + node.attributeValue("name") + "节点路径为:" + node.getPath());String nodePath = node.getPath();logger.info("父节点的名称为:" + node.getParent().attributeValue("name"));// 如果当前节点的父节点为根节点if (node.attributeValue("name") == rootName) {logger.info(node.attributeValue("name") + " 不存在多层路径");currentSuiteName = node.attributeValue("name");testcasePathCell.setCellValue(currentSuiteName);} else {getTestCasePath(nodePath);List testSuitePathList = new ArrayList();// 当前节点的名称currentSuiteName = node.attributeValue("name");System.out.println("--------------------------------当前节点的名称为:-----------------------" + currentSuiteName);parentNode = node.getParent();String currentParentSuiteName = parentNode.attributeValue("name");logger.info("-------------------------------当前节点的父节点名称为:----------------------" + currentParentSuiteName);// 当前节点不为根节点while (parentNode.attributeValue("name") != rootName) {// 替换父节点parentNode = parentNode.getParent();// 获得父节点的属性值String testSuiteName = parentNode.attributeValue("name");// 如果非父节点if (testSuiteName != "") {testSuitePathList.add(testSuiteName);logger.info("-------------------------------------------------------" + testSuiteName);}}StringBuffer stringBuffer = new StringBuffer();Collections.reverse(testSuitePathList);// 获得用例路径for (String suiteName : testSuitePathList) {stringBuffer.append(suiteName + "/");}String testcaseFullPath = stringBuffer + currentParentSuiteName + "/" + currentSuiteName;logger.info("用例完整路径为:" + testcaseFullPath);if (testcaseFullPath != null && testcasePathCell != null) {testcasePathCell.setCellValue(testcaseFullPath);// 写入用例路径到Excel}}}// testsuite为根节点if (nodeName.equals("testsuite") && node.element("testcase") != null && node.isRootElement()) {// 非根节点且包含测试用例// 创建测试用例路径单元格// 测试用例路径logger.info("非多步骤创建第" + testcaseRowNum + "行");// cell.setCellStyle(style);testcaseRow = caseSheet.createRow(testcaseRowNum);Cell testcasePathCell = testcaseRow.createCell(0);String currentSuiteName = null;// testcasePathCell.setCellStyle(style);logger.info("===================节点名称为:" + node.attributeValue("name") + "节点路径为:" + node.getPath());String nodePath = node.getPath();// logger.info("父节点的名称为:" + node.getParent().attributeValue("name"));// 如果当前节点的父节点为根节点if (node.attributeValue("name") == rootName) {logger.info(node.attributeValue("name") + " 不存在多层路径");currentSuiteName = node.attributeValue("name");testcasePathCell.setCellValue(currentSuiteName);} else {getTestCasePath(nodePath);List testSuitePathList = new ArrayList();// 当前节点的名称currentSuiteName = node.attributeValue("name");System.out.println("--------------------------------当前节点的名称为:-----------------------" + currentSuiteName);parentNode = node.getParent();String currentParentSuiteName = parentNode.attributeValue("name");logger.info("-------------------------------当前节点的父节点名称为:----------------------" + currentParentSuiteName);// 当前节点不为根节点while (parentNode.attributeValue("name") != rootName) {// 替换父节点parentNode = parentNode.getParent();// 获得父节点的属性值String testSuiteName = parentNode.attributeValue("name");// 如果非父节点if (testSuiteName != "") {testSuitePathList.add(testSuiteName);logger.info("-------------------------------------------------------" + testSuiteName);}}StringBuffer stringBuffer = new StringBuffer();Collections.reverse(testSuitePathList);// 获得用例路径for (String suiteName : testSuitePathList) {stringBuffer.append(suiteName + "/");}String testcaseFullPath = stringBuffer + currentParentSuiteName + "/" + currentSuiteName;logger.info("用例完整路径为:" + testcaseFullPath);if (testcaseFullPath != null && testcasePathCell != null) {testcasePathCell.setCellValue(testcaseFullPath);// 写入用例路径到Excel}}}// 获取用例的名称if (nodeName.equals("testcase") && node.getParent().getName().equals("testsuite") && !node.isRootElement()) {logger.info("用例名称为:" + node.attributeValue("name"));String testcaseName = node.attributeValue("name");Cell testcaseNameCell = testcaseRow.createCell(1);// testcaseNameCell.setCellStyle(style);// 设置边框if (testcaseNameCell != null) {logger.info("正常创建用例....用例名称为:" + testcaseName + "坐标为:" + testcaseRowNum + "行" + "1列");testcaseNameCell.setCellValue(testcaseName);} else {logger.info("创建用例" + testcaseName + "失败当前为:" + testcaseRowNum + "行");}// 获取用例的描述if (node.element("summary") != null) {String summary = node.element("summary").getStringValue().replaceAll("", "").replaceAll("
", "\r").replaceAll("", "\r").replaceAll("&ldquo", "\"").replaceAll("&rdquo", "\"").replaceAll("
", "");logger.info("用例摘要为:" + summary);Cell testcaseSummaryCell = testcaseRow.createCell(2);// testcaseSummaryCell.setCellStyle(style);if (testcaseSummaryCell != null) {testcaseSummaryCell.setCellValue(summary);}}// 获取用例的优先级if (node.element("importance") != null) {String importance = node.element("importance").getStringValue();logger.info("用例优先级为:" + importance);// logger.info("用例摘要为:" + importance);Cell testcaseimportanceCell = testcaseRow.createCell(3);// testcaseimportanceCell.setCellStyle(style);if (testcaseimportanceCell != null) {if (importance.equals("3")) {importance = "高";}if (importance.equals("2")) {importance = "中";}if (importance.equals("1")) {importance = "低";}testcaseimportanceCell.setCellValue(importance);}}// 获取用例的前提if (node.element("preconditions") != null) {String preconditions = node.element("preconditions").getStringValue().replaceAll("", "").replaceAll("
", "\r").replaceAll("", "\r").replaceAll("&ldquo", "\"").replaceAll("&rdquo", "\"").replaceAll("
", "").replaceAll(" ", "");logger.info("用例的前提为:" + preconditions);Cell testcasePreconditionsCell = testcaseRow.createCell(4);// testcasePreconditionsCell.setCellStyle(style);if (testcasePreconditionsCell != null && preconditions != null) {testcasePreconditionsCell.setCellValue(preconditions);}}}// 获取用例操作步骤eif (nodeName.equals("steps")) {// testcaseRow = caseSheet.createRow(testcaseRowNum);if (node.elements("step") != null) {List stepList = node.elements("step");logger.info("==============步骤长度为:" + stepList.size());int stepLen = stepList.size();for (Element stElement : stepList) {Cell testcaseActionsCell = testcaseRow.createCell(5);// testcaseActionsCell.setCellStyle(style);Cell testcaseExpectedresultsCell = testcaseRow.createCell(6);// testcaseExpectedresultsCell.setCellStyle(style);if (stElement.element("actions") != null) {Node element = stElement.element("actions");String actions = element.getStringValue().replaceAll("", "").replaceAll("
", "\r").replaceAll("", "\r").replaceAll("&ldquo", "\"").replaceAll("&rdquo", "\"").replaceAll("
", "").replaceAll(" ", "");if (testcaseActionsCell != null && actions != null) {testcaseActionsCell.setCellValue(actions);}}// 获取期望结果if (stElement.element("expectedresults") != null) {Node element = stElement.element("expectedresults");String expectedresults = element.getStringValue().replaceAll("", "").replaceAll("
", "\r").replaceAll("", "\r").replaceAll("&ldquo", "\"").replaceAll("&rdquo", "\"").replaceAll("
", "").replaceAll(" ", "");if (testcaseExpectedresultsCell != null && expectedresults != null) {testcaseExpectedresultsCell.setCellValue(expectedresults);}}testcaseRowNum++;// 用例有多条步骤if (stepLen > 2) {logger.info("用例步骤大于2条,当前行号为:" + testcaseRowNum);logger.info("多步骤创建第" + testcaseRowNum + "行");testcaseRow = caseSheet.createRow(testcaseRowNum);} else {// 针对非多步骤的用例if (stepLen <= 2 && node.getParent().getName().equals("testcase")) {testcaseRow = caseSheet.createRow(testcaseRowNum);}logger.info("当前为==================" + testcaseRow.getRowNum() + "行");}}}}// 递归遍历当前节点所有的子节点List listElement = node.elements();// 所有一级子节点的listfor (Element e : listElement) {// 遍历所有一级子节点// logger.info("递归的子节点元素数目为 :" + e.attributeCount() + " 递归的子节点元素名称为" +// e.getName());getNodes(e);// 递归}}/*** 获取用例路径 ** @param testCasePath 获取到的xml中的原始路径*/public static void getTestCasePath(String testCasePath) {String[] a = testCasePath.split("/");if (a.length != 0) {// 0表示空、1表示根节点,需要去掉根节点的路径for (int i = 0; i < a.length; i++) {if (i != 0 && i != 1) {logger.info(a[i]);}}}}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
