【问题标题】:Generate XML from template and fill it with new data从模板生成 XML 并用新数据填充它
【发布时间】:2011-07-01 14:20:27
【问题描述】:


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

谢谢

【问题讨论】:

    标签: xml


    【解决方案1】:

    【讨论】:

    • 我觉得会很复杂,但我会试试
    • 只根据您的要求复杂 - 首先尝试一些简单的方法,例如 SELECT * FROM Customers FOR XML AUTO、返回 XML 数据类型的 TYPE 或 SELECT * FROM Customers FOR XML AUTO 将 XML 内容作为varchar
    • 看来我的问题类似于stackoverflow.com/questions/4267427/…
    【解决方案2】:

    @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' />"
    

    【讨论】:

      【解决方案3】:
      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();
              }
                  }
      }
      

      【讨论】:

        【解决方案4】:
            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
        

        【讨论】:

        • 你的代码应该有一些 cmets 来帮助人们理解你在做什么。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多