从模板生成XML并用新数据填充它

时间:2011-07-01 14:20:28

标签: xml


我有一些XML(超过150个标签) 我需要根据该模板创建额外的50 xml文件,但需要使用其他标记值 所以我已经生成了随机数据(以xls,csv,sql格式保存),我需要在模板中填充这些值并使用新名称保存。 我怎么能这样做? (unix shell脚本,java,软件等)

感谢

4 个答案:

答案 0 :(得分:0)

  

假设您能够使用SQL Server - 请查看FOR XML

http://msdn.microsoft.com/en-us/library/ms345137%28v=sql.90%29.aspx#forxml2k5_topic4

答案 1 :(得分:0)

@BonyT,谢谢,你告诉我正确的方向,我正在使用db2,所以对我来说回答是:

db2 => EXPORT TO "c:\temp\xml.del" OF DEL XML TO "c:\temp\xml" XMLFILE "xml" MESSAGES "c:\temp\msg.txt" SELECT * FROM TMP.XML_TEMPLATE


其中xml.del(所有生成的XML保存在一个文件c:\temp\xml\tmp_xml2.001.xml中 - 我没有找到单独保存XML的方法)

6,"<XDS FIL='tmp_xml2.001.xml' OFF='0' LEN='34780' />"
5,"<XDS FIL='tmp_xml2.001.xml' OFF='34780' LEN='34780' />"
7,"<XDS FIL='tmp_xml2.001.xml' OFF='69560' LEN='34780' />"

答案 2 :(得分:0)

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.Set;
    import java.util.TreeSet;
    import org.apache.poi.common.usermodel.*;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.w3c.dom.Attr;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Text;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.*;

    public class XMLConversion {
        private static void buildEntryList(List<String> entries,
                String parentXPath, Element parent) {
            NamedNodeMap attrs = parent.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                Attr attr = (Attr) attrs.item(i);
                // TODO: escape attr value
                entries.add(parentXPath + "[@" + attr.getName() + "='"
                        + attr.getValue().trim() + "']");
            }
            HashMap<String, Integer> nameMap = new HashMap<String, Integer>();
            NodeList children = parent.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child instanceof Text) {
                    // TODO: escape child value
                    entries.add(parentXPath + "='"
                            + ((Text) child).getData().trim() + "'");
                } else if (child instanceof Element) {
                    String childName = child.getNodeName();
                    Integer nameCount = nameMap.get(childName);
                    nameCount = nameCount == null ? 1 : nameCount + 1;
                    nameMap.put(child.getNodeName(), nameCount);
                    buildEntryList(entries, parentXPath + "/" + childName + "["
                            + nameCount + "]", (Element) child);
                }
            }
        }

        public static List<String> getEntryList(Document doc) {
            ArrayList<String> entries = new ArrayList<String>();
            Element root = doc.getDocumentElement();

            entries.add("/" + root.getNodeName() + "[1]" + "='" + "'");
            buildEntryList(entries, "/" + root.getNodeName() + "[1]", root);
            return entries;
        }


        public int createExcelForXML(Set<String> xPathSet,String targetExcelFileName,String fileTestCaseName) throws IOException{
            HSSFWorkbook xmlWorkBook = new HSSFWorkbook();
            HSSFSheet xmlSheet = xmlWorkBook
                    .createSheet("XML Unit Testing Template");
            int excelCellNum=0;
            HSSFRow xmlSheetRow = null;
            HSSFCell xmlRowCell = null;
            String[] headerRowElements = {fileTestCaseName+"_TC1","XPaths"};
            for(int excelRowNum=0;excelRowNum<=1;excelRowNum++){

                if(excelRowNum==0){
                    excelCellNum=2;
                }
                else
                    excelCellNum=1;
                xmlSheetRow = xmlSheet.createRow(excelRowNum);
                xmlRowCell = xmlSheetRow.createCell(excelCellNum);
                xmlRowCell.setCellValue(headerRowElements[excelRowNum]);
            }
            int excelRowNum=2;
        //  for(int excelRowNum=2;excelRowNum<=xPathSet.size();excelRowNum++){
            for(String xPaths : xPathSet){

                int currentCellNum=1;
                String xmlXpath=null;
                String xmlTextContent=null;
                xmlSheetRow = xmlSheet.createRow(excelRowNum);
                xmlXpath=xPaths.substring(0,xPaths.indexOf("="));
                xmlTextContent=xPaths.substring(xPaths.indexOf("=")+2,xPaths.lastIndexOf("'"));
                for(int currCellNum=1;currCellNum<=2;currCellNum++){

                    if(currCellNum==1){
                        xmlRowCell = xmlSheetRow.createCell(currCellNum);
                        xmlRowCell.setCellValue(xmlXpath);
                    }
                    else{
                        xmlRowCell = xmlSheetRow.createCell(currCellNum);
                        xmlRowCell.setCellValue(xmlTextContent);
                    }


            }
excelRowNum++;
            }
            String tempExcelPath=new File(targetExcelFileName).getParent();
            System.out.println(tempExcelPath);
            tempExcelPath=tempExcelPath.substring(6,tempExcelPath.length());
            System.out.println(tempExcelPath);
            String targetExcelFullPath = tempExcelPath+"\\"+fileTestCaseName+".xls";
            FileOutputStream excelOutput = new FileOutputStream(new File(targetExcelFullPath));

            xmlWorkBook.write(excelOutput);
            System.out.println("done");
            return 1;
        }

        public boolean parseXMLandCreateExcel(String fileName) throws Exception{
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            docFactory.setNamespaceAware(false);
            int fileIndex=0;
            String fileTestCaseName=null;
            String targetPathName=null;
            int isFileXML=0;
            if(fileName.endsWith(".xml")){
                isFileXML=1;
            }
            if(isFileXML!=0){       
            if(fileName.contains("\\")){
                fileIndex=fileName.lastIndexOf("\\")+1;
            }}
            else 
                throw new Exception("You have not provided an XML to parse it. Please provide an XML file");


            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            Document doc = docBuilder.parse(new File(fileName));
            fileTestCaseName=fileName.substring(fileIndex, fileName.lastIndexOf("."));
            targetPathName=doc.getBaseURI();
        //  targetPathName=targetPathName.substring(0,doc.getBaseURI().lastIndexOf("."));
            if(fileTestCaseName==null){
                throw new Exception("The XML Conversion has encountered an error in getting the FileName for the Excel to be generated. Please try to resolve it.");
            }
            if(targetPathName==null){
                throw new Exception("The XML Conversion has encountered an error in getting the Target Path for the Excel to be generated. Please try to resolve it.");
            }
            List<String> xmlList = new ArrayList<String>();
            xmlList = getEntryList(doc);
            Set<String> linkedSet = new LinkedHashSet<String>(xmlList);
            /*for (String xmlL : linkedSet) {
                System.out.println(xmlL);
            }
            */
            System.out.println();
            System.out.println(targetPathName);
            createExcelForXML(linkedSet,targetPathName,fileTestCaseName);
            return true;
        }

        public static void main(String[] args){

            String fileName = "sample1.xml";

            //System.out.println(fileName.substring(fileIndex, fileName.lastIndexOf(".")));

            XMLConversion parseXMLDocument=new XMLConversion();
            try {
                parseXMLDocument.parseXMLandCreateExcel(fileName);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                }
    }

        enter code here

答案 3 :(得分:0)

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.poi.common.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;

public class XMLConversion {
    private static void buildEntryList(List<String> entries,
            String parentXPath, Element parent) {
        NamedNodeMap attrs = parent.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Attr attr = (Attr) attrs.item(i);
            // TODO: escape attr value
            entries.add(parentXPath + "[@" + attr.getName() + "='"
                    + attr.getValue().trim() + "']");
        }
        HashMap<String, Integer> nameMap = new HashMap<String, Integer>();
        NodeList children = parent.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child instanceof Text) {
                // TODO: escape child value
                entries.add(parentXPath + "='"
                        + ((Text) child).getData().trim() + "'");
            } else if (child instanceof Element) {
                String childName = child.getNodeName();
                Integer nameCount = nameMap.get(childName);
                nameCount = nameCount == null ? 1 : nameCount + 1;
                nameMap.put(child.getNodeName(), nameCount);
                buildEntryList(entries, parentXPath + "/" + childName + "["
                        + nameCount + "]", (Element) child);
            }
        }
    }

    public static List<String> getEntryList(Document doc) {
        ArrayList<String> entries = new ArrayList<String>();
        Element root = doc.getDocumentElement();

        entries.add("/" + root.getNodeName() + "[1]" + "='" + "'");
        buildEntryList(entries, "/" + root.getNodeName() + "[1]", root);
        return entries;
    }


    public int createExcelForXML(Set<String> xPathSet,String targetExcelFileName){
        HSSFWorkbook xmlWorkBook = new HSSFWorkbook();
        HSSFSheet xmlSheet = xmlWorkBook
                .createSheet("XML Unit Testing Template");
        int excelCellNum=0;
        HSSFRow xmlSheetRow = null;
        HSSFCell xmlRowCell = null;
        String[] headerRowElements = {targetExcelFileName+"_TC1","XPaths"};
        for(int excelRowNum=0;excelRowNum<=1;excelRowNum++){

            if(excelRowNum==0){
                excelCellNum=2;
            }
            else
                excelCellNum=1;
            xmlSheetRow = xmlSheet.createRow(excelRowNum);
            xmlRowCell = xmlSheetRow.createCell(excelCellNum);
            xmlRowCell.setCellValue(headerRowElements[excelRowNum]);
        }
        int excelRowNum=2;
    //  for(int excelRowNum=2;excelRowNum<=xPathSet.size();excelRowNum++){
        for(String xPaths : xPathSet){

            int currentCellNum=1;
            String xmlXpath=null;
            String xmlTextContent=null;
            xmlSheetRow = xmlSheet.createRow(excelRowNum);
            xmlXpath=xPaths.substring(0,xPaths.indexOf("="));
            xmlTextContent=xPaths.substring(xPaths.indexOf("="),xPaths.lastIndexOf("'"));
            for(int currCellNum=1;currCellNum<=2;currCellNum++){

                if(currCellNum==1){
                    xmlRowCell = xmlSheetRow.createCell(currCellNum);
                    xmlRowCell.setCellValue(xmlXpath);
                }
                else{
                    xmlRowCell = xmlSheetRow.createCell(currCellNum);
                    xmlRowCell.setCellValue(xmlTextContent);
                }

            excelRowNum++;
        }
        }
        //FileOutputS
        return 1;
    }

    public boolean parseXMLandCreateExcel(String fileName) throws Exception{
        DocumentBuilderFactory docFactory = DocumentBuilderFactory
                .newInstance();
        docFactory.setNamespaceAware(false);
        int fileIndex=0;
        String fileTestCaseName=null;
        String targetPathName=null;
        int isFileXML=0;
        if(fileName.endsWith(".xml")){
            isFileXML=1;
        }
        if(isFileXML!=0){       
        if(fileName.contains("\\")){
            fileIndex=fileName.lastIndexOf("\\")+1;
        }}
        else 
            throw new Exception("You have not provided an XML to parse it. Please provide an XML file");


        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.parse(new File(fileName));
        fileTestCaseName=fileName.substring(fileIndex, fileName.lastIndexOf("."));
        targetPathName=doc.getBaseURI();
        targetPathName=targetPathName.substring(0,doc.getBaseURI().lastIndexOf("."));
        if(fileTestCaseName==null){
            throw new Exception("The XML Conversion has encountered an error in getting the FileName for the Excel to be generated. Please try to resolve it.");
        }
        if(targetPathName==null){
            throw new Exception("The XML Conversion has encountered an error in getting the Target Path for the Excel to be generated. Please try to resolve it.");
        }
        List<String> xmlList = new ArrayList<String>();
        xmlList = getEntryList(doc);
        Set<String> linkedSet = new LinkedHashSet<String>(xmlList);
        /*for (String xmlL : linkedSet) {
            System.out.println(xmlL);
        }
        */
        System.out.println();
        System.out.println(targetPathName);

        return true;
    }

    public static void main(String[] args){

        String fileName = "sample1.xml";

        //System.out.println(fileName.substring(fileIndex, fileName.lastIndexOf(".")));

        XMLConversion parseXMLDocument=new XMLConversion();
        try {
            parseXMLDocument.parseXMLandCreateExcel(fileName);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            }
}