【问题标题】:How to write from a text files to one xml如何从文本文件写入一个 xml
【发布时间】:2014-11-13 01:03:21
【问题描述】:

我想将多个文本文件写入一个 xml 文件。以下是三个示例数据集

data1.txt

 Name    Score
 Leslie  25
 Pat     12
 Alfred  32

data2.txt

Name    Score
Leslie  35
Keith   22
Alfred  12

data3.txt

Name    Score
Philip  38
Keith   32
Diop    22

用于完成这项工作的代码如下:

public class Modify {
public static void main(String argv[]) throws IOException {
    List<String> name = new ArrayList<String>();
    List<String> score = new ArrayList<String>();


    String path = "C:/Users/yawa/Desktop/INRIX Database/InrixDataProc/question/";

    String textfile;
    // reading data 
    File folder = new File(path);

    File [] listOfFiles = folder.listFiles(new FilenameFilter(){

        @Override
        public boolean accept(File folder, String name){
            return name.endsWith(".txt");               
        }
    });

    for (int ixa=0; ixa<listOfFiles.length; ixa++){

        textfile = listOfFiles[ixa].getName();
         String inputfile = textfile;

         FileReader fr1 = new FileReader(inputfile);
         BufferedReader bfr1 = new BufferedReader(fr1);
         String aLine1;
         while ((aLine1 = bfr1.readLine()) != null) {
             String[] split = aLine1.split("\t");
             name.add(split[0]); score.add(split[1]);

         }
    bfr1.close();
 // writing data to xml       
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try{
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();
         Element rootElement =doc.createElementNS("http://www.journaldev.com/employee", "Employees");

         doc.appendChild(rootElement);
         for (int ix=1; ix<name.size(); ix++){
             rootElement.appendChild(getEmployee(doc,name.get(ix),score.get(ix)));
         }

         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         //for pretty print
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
         DOMSource source = new DOMSource(doc);

         StreamResult console = new StreamResult(System.out);
         StreamResult filexx = new StreamResult(new File("C:/Users/yawa/Desktop/INRIX Database/InrixDataProc/brxxx.xml"));

         //write data
         transformer.transform(source, console);
         transformer.transform(source, filexx);


    }catch(Exception e) {
        e.printStackTrace();

    }

    }
}

private static Node getEmployee(Document doc, String id, String score){
    Element employee = doc.createElement("Employee");
    employee.setAttribute("id", id);
    employee.appendChild(getEmployeeElements(doc,employee,"score", score));
    return employee;
}

private static Node getEmployeeElements (Document doc, Element element, String name,String value){
    Element node = doc.createElement(name);
    node.appendChild(doc.createTextNode(value));
    return node;    
}

}

当前结果

<?xml version="1.0" encoding="UTF-8"?>
-<Employees xmlns="http://www.journaldev.com/employee">
-<Employee id="Leslie">
<score>25</score>
</Employee>
-<Employee id="Pat">
<score>12</score>
</Employee>
-<Employee id="Alfred">
<score>32</score>
</Employee>
-<Employee id="Name">
 <score>Score</score>
 </Employee>
 -<Employee id="Leslie">
 <score>35</score>
 </Employee>
 -<Employee id="Keith">
 <score>22</score>
 </Employee>
 -<Employee id="Alfred">
 <score>12</score>
 </Employee>
 -<Employee id="Name">
 <score>Score</score>
 </Employee>
 -<Employee id="Philip">
 <score>38</score>
 </Employee>
 -<Employee id="Keith">
 <score>32</score>
 </Employee>
 -<Employee id="Diop">
 <score>22</score>
 </Employee>
 </Employees>

如果 xml 文件中已经存在 Employee id,我想替换它。同时,我希望能够增加新员工。当前代码无法替换现有条目

【问题讨论】:

    标签: java xml parsing text


    【解决方案1】:
    private static Node getEmployeeById(Document doc, String id) {
        if (doc == null) {
            throw new IllegalArgumentException("doc must not be null");
        }
        if (id == null) {
            throw new IllegalArgumentException("id must not be null");
        }
    
        XPath xpath = XPathFactory.newInstance().newXPath();
        String path = "//Employee[@id = '" + id + "']";
    
        try {
            NodeList nl = (NodeList) xpath.evaluate(path, doc, XPathConstants.NODESET);
            return nl.getLength() > 0 ? nl.item(0) : null;
        } catch (XPathExpressionException ex) {
            return null;
        }
    }
    

    我相信你可以弄清楚其余的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-30
      • 2021-12-04
      • 2021-07-17
      • 2015-02-02
      • 2017-07-26
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多