java 如何在java中创建一个xml文件并将数据从用户输入附加到其中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14359760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:00:25  来源:igfitidea点击:

How to create an xml file in java and append data into it from user input

javaxmlappend

提问by souvik

I have created the xml file but problem is the when I am adding additional data it is being overwritten..I need a code which creates a new xml file if it doesnt exist or append to a xml file if it does exit...I am creating a log file which keeps the record of transactions

我已经创建了 xml 文件,但问题是当我添加其他数据时,它被覆盖了..我需要一个代码来创建一个新的 xml 文件,如果它不存在,或者附加到一个 xml 文件,如果它退出......我我正在创建一个记录交易记录的日志文件

Here is the code:

这是代码:

import java.io.*;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

 public class Log_XML {

  static String transaction_type, shop_no, terminal_no;

  static int id = 0;

  public static void main(String[] args) throws IOException, DOMException {
    System.out.println("Enter Id : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    id = Integer.parseInt(br.readLine());

    System.out.println("Enter Transaction type : ");
    transaction_type = br.readLine();

    System.out.println("Shop no : ");
    shop_no = br.readLine();

    System.out.println(“Terminal no : “);
    terminal_no = br.readLine();
     write_XML_File(id);
   }

   public static void write_XML_File(int id) {
      String id_val = Integer.toString(id);
      try {
         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

         Document doc = docBuilder.newDocument();

         Element log1 = doc.createElement("log");
         doc.appendChild(log1);

         Attr attr = doc.createAttribute("id");
         attr.setValue(id_val);
         log1.setAttributeNode(attr);

         Element transaction_type1 = doc.createElement("transaction_type");
         transaction_type1.appendChild(doc.createTextNode(transaction_type));
         log1.appendChild(transaction_type1);

         Element shop_no1 = doc.createElement("shop_no");
         shop_no1.appendChild(doc.createTextNode(shop_no));
         log1.appendChild(shop_no1);

         Element terminal_no1 = doc.createElement("terminal_no");
         terminal_no1.appendChild(doc.createTextNode(terminal_no));
         log1.appendChild(terminal_no1);

          TransformerFactory transformerFactory = TransformerFactory.newInstance();
          Transformer transformer = transformerFactory.newTransformer();
           transformer.setOutputProperty(OutputKeys.INDENT, "yes");
           DOMSource source = new DOMSource(doc);
           StreamResult result = new StreamResult(new File("D:/log_file.xml"));
           transformer.transform(source, result);

           System.out.println("File saved!");
           } catch (ParserConfigurationException e) {
                e.printStackTrace();
           } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
         }
     }
  }

采纳答案by Alain Faure

Well, XML is not designed to be appended, because it is seen as a tree with a root element. Something like:

嗯,XML 不是为了附加而设计的,因为它被视为带有根元素的树。就像是:

<MyRoot>
<innerEll/>
</Myroot>

Once is written you cannot append anything, in that case the solution is as in previous post : reRead it, add your new log.... but I don't think it will performm well!

一旦写入,您将无法追加任何内容,在这种情况下,解决方案与之前的帖子相同:重新阅读它,添加您的新日志......但我认为它不会表现得很好!

If you decided to use a file with XML syntax but without the Root node, something like

如果您决定使用具有 XML 语法但没有 Root 节点的文件,则类似于

<log> .... </log>
<log> .... </log>

you can then create the StreamResult from a StringWriter instead of a file. Then you can get the string from the StringWriter and use standard File api to append the string.

然后,您可以从 StringWriter 而不是文件创建 StreamResult。然后您可以从 StringWriter 获取字符串并使用标准 File api 附加字符串。

Note that you may have to "filter out" the string of some Xml declaration that can be before your main node.

请注意,您可能必须“过滤掉”可能位于主节点之前的某些 Xml 声明的字符串。

Alternatively if the XML you want to generate is quite simple it is often easier to do it by hand:

或者,如果您要生成的 XML 非常简单,则手动生成通常更容易:

myXML = "<log><Id>" + escapeXML(myId) + "</Id>...

escapeXML function is needed in case you have things like "<" in your string. There are many libraries to do this (or you can implement a simple thing adapted to your strings). Alternatively you can use CDATA if it gets too complicated.

如果字符串中有“<”之类的内容,则需要escapeXML 函数。有很多库可以做到这一点(或者你可以实现一个适合你的字符串的简单东西)。或者,如果它变得太复杂,您可以使用 CDATA。

回答by Dave Newton

If the file exists: parse it, append new content at the appropriate location.

如果文件存在:解析它,在适当的位置附加新内容。

If it doesn't: do what you're doing now.

如果没有:做你现在正在做的事情。

I'd re-use the appending code by either: creating a DOM and appending the new content as mentioned earlier, or by keeping a DOM shell file in the jar as a resource and using it as a default document.

我会通过以下任一方式重新使用附加代码:创建一个 DOM 并附加前面提到的新内容,或者将 DOM shell 文件作为资源保存在 jar 中并将其用作默认文档。