维护从XML到Excel文件的层次结构-Java
我有一个包含嵌套记录的XML文件。我必须从文件中获取记录并写入Excel文件。现在,我制作的文件是平面文件。(我使用ApachePOI写入Excel文件)。我需要它来维护层次结构信息,以便嵌套记录缩进 我的XML文件如下所示:维护从XML到Excel文件的层次结构-Java,java,xml,excel,apache-poi,hierarchical-data,Java,Xml,Excel,Apache Poi,Hierarchical Data,我有一个包含嵌套记录的XML文件。我必须从文件中获取记录并写入Excel文件。现在,我制作的文件是平面文件。(我使用ApachePOI写入Excel文件)。我需要它来维护层次结构信息,以便嵌套记录缩进 我的XML文件如下所示: <node> <id>123</id> <label>ABC</label> <node> <id>456</id> &
<node>
<id>123</id>
<label>ABC</label>
<node>
<id>456</id>
<label>DEF</label>
....... so on
123
基础知识
456
DEF
....... 等等
我当前的Excel如下所示:
我需要这样的东西(用XML文件表示层次结构):
有人有过类似的经历吗?我非常感谢您的帮助。如果您愿意测试Sax解析器,我可能会有一个解决方案供您尝试。下面是我使用的类,它包含SAXParser的默认处理程序,以及在将xml文件输入xlsx文件之前用于格式化xml文件的代码。它看起来有点沉重,所以我尽可能地添加评论,试图让它变得易懂
public class SO2 {
private SO2(File xml){
wb = new XSSFWorkbook(); //Workbook to create
sheet = wb.createSheet(); //Sheet to write to
try {
SO2.retrieveSaxParser().parse(xml, SO2.retrieveHandler()); //Begin parse
Path file = Paths.get(System.getProperty("user.home"), "Desktop", "XMLTest.xlsx"); //Where to write file
wb.write(new FileOutputStream(file.toString()));
} catch (SAXException | IOException | ParserConfigurationException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
System.exit(0);
}
protected static void instertUpdate(String data, int columnNum, int rowNum) {//Method to add to spreadsheet
/*The below writes to the file, the row if statements are there to stop the method
* overwriting any rows already created
*/
if(row != null){
if(row.getRowNum() != rowNum){
row = sheet.createRow(rowNum);
}
} else {
row = sheet.createRow(rowNum);
}
cell = row.createCell(columnNum);//Make our cell
cell.setCellValue(data);//Write to it
}
private static SAXParser retrieveSaxParser() throws ParserConfigurationException, SAXException{
return SAXParserFactory.newInstance().newSAXParser();//Get parser
}
private static DefaultHandler retrieveHandler() {
DefaultHandler handler = new DefaultHandler(){//Handler with methods required for parsing xml
@Override
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
if(startWasPrevious == true){//Start indenting after the first element tag processed
indent++;
}
rowNumber++;//Move row down for each tag
columnNumber = indent; //Cell number set to current indent level
SO2.instertUpdate("<" + qName + ">", columnNumber, rowNumber);//Insert
startWasPrevious = true; //For formatting
previous = startTag;//For formatting
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(startWasPrevious == false){//For removal of indentation
indent--;
}
if(!previous.equals("text")){//If text wasn't last part parsed then set column to indent
columnNumber = indent;
} else{//If text was processed last move cell across
columnNumber++;
}
if(previous.equals("end")){//Move to a newline if last parsed element was an ending tag
rowNumber++;
}
if(startWasPrevious == false){ //If there was no text previously
SO2.instertUpdate("</" + qName + ">", columnNumber, rowNumber);
} else { //If there was text then this will be enclosing end tag
SO2.instertUpdate("</" + qName + ">", columnNumber, rowNumber);
}
startWasPrevious = false; //For formatting
previous = endTag;
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length).trim();//Get text
if(s.length() > 0){
columnNumber++; //Move column number along
SO2.instertUpdate(s, columnNumber, rowNumber);
previous = text;
}
}
};
return handler;
}
//Main
public static void main(String[] args) {
JFrame file = new JFrame("File choice. . .");
file.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
FileDialog dialog = new FileDialog(file, "Choose a file", FileDialog.LOAD);//Get XML File
dialog.setDirectory(Paths.get(System.getProperty("user.home")).resolve("Desktop").toString());
dialog.setFile("*.xml");
dialog.setVisible(true);
if(dialog.getFile() == null){
System.exit(0);
} else {
xmlFile = new File(dialog.getDirectory() + dialog.getFile());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SO2(xmlFile);
}
});
}
}
private static File xmlFile;
private static XSSFWorkbook wb;
private static Sheet sheet;
private static Row row;
private static Cell cell;
private static boolean startWasPrevious = false; //For formatting purposes
private static int rowNumber = -1; //Hold row number
private static int columnNumber = 0;//Hold number of cell to wtite to
private static int indent;//For indenting
private static String previous = "";//To know what was last processed
private static final String endTag = "end";//Values for previous to hold
private static final String text = "text";//Values for previous to hold
private static final String startTag = "start";//Values for previous to hold
}
公共类SO2{
私有SO2(文件xml){
wb=new XSSFWorkbook();//要创建的工作簿
sheet=wb.createSheet();//要写入的工作表
试一试{
SO2.retrieveSaxParser().parse(xml,SO2.retrieveHandler());//开始解析
Path file=Path.get(System.getProperty(“user.home”),“Desktop”,“XMLTest.xlsx”);//在哪里写入文件
write(新文件输出流(file.toString());
}捕获(SAXException | IOException | ParserConfiguration异常e){
showMessageDialog(null,e.getMessage());
}
系统出口(0);
}
受保护的静态void instertUpdate(字符串数据,int columnNum,int rowNum){//要添加到电子表格的方法
/*下面的语句写入文件,行if语句用于停止该方法
*覆盖已创建的任何行
*/
如果(行!=null){
if(row.getRowNum()!=rowNum){
行=sheet.createRow(rowNum);
}
}否则{
行=sheet.createRow(rowNum);
}
cell=row.createCell(columnNum);//生成我们的单元格
cell.setCellValue(数据);//写入
}
私有静态SAXParser retrieveSaxParser()抛出ParserConfiguration异常,SAXException{
返回SAXParserFactory.newInstance().newSAXParser();//获取解析器
}
私有静态DefaultHandler retrieveHandler(){
DefaultHandler=new DefaultHandler(){//handler,包含解析xml所需的方法
@凌驾
public void startElement(字符串uri、字符串localName、字符串qName、属性)引发SAXException{
如果(startWasPrevious==true){//在处理第一个元素标记后开始缩进
缩进++;
}
rowNumber++;//为每个标记下移行
columnNumber=indent;//单元格编号设置为当前缩进级别
SO2.insertupdate(“,columnNumber,rowNumber);//插入
startWasPrevious=true;//用于格式化
previous=startTag;//用于格式化
}
@凌驾
public void endElement(字符串uri、字符串localName、字符串qName)引发SAXException{
如果(startWasPrevious==false){//用于移除压痕
缩进--;
}
若(!previous.equals(“text”){//若未解析文本的最后一部分,则将列设置为缩进
columnNumber=缩进;
}else{//如果文本是最后一次处理的,则将单元格移动到另一个单元格
columnNumber++;
}
if(previous.equals(“end”){//如果最后解析的元素是结束标记,则移动到换行符
行数++;
}
if(startWasPrevious==false){//如果之前没有文本
SO2.InsertUpdate(“,列号,行号);
}else{//如果有文本,则这将是封闭的结束标记
SO2.InsertUpdate(“,列号,行号);
}
startWasPrevious=false;//用于格式化
previous=endTag;
}
@凌驾
公共无效字符(char ch[],int start,int length)引发异常{
String s=新字符串(ch,start,length).trim();//获取文本
如果(s.长度()>0){
columnNumber++;//移动列号
SO2.仪表更新(s、列号、行号);
先前=文本;
}
}
};
返回处理程序;
}
//主要
公共静态void main(字符串[]args){
JFrame file=newjframe(“文件选择…”);
file.setDefaultCloseOperation(JFrame.DISPOSE\u ON\u CLOSE);
FileDialog=newfiledialog(文件,“选择文件”,FileDialog.LOAD);//获取XML文件
setDirectory(path.get(System.getProperty(“user.home”)).resolve(“Desktop”).toString());
dialog.setFile(“*.xml”);
对话框.setVisible(true);
if(dialog.getFile()==null){
系统出口(0);
}否则{
<?xml version="1.0"?>
<empire>
<darkness>
<sith>
<title>Darth</title>
<name>Vader</name>
<power>Grip</power>
</sith>
<sith>
<title>Darth</title>
<name>Sidious</name>
<power>Lightning</power>
</sith>
</darkness>