Java - 如何将XML元素添加到根标记?

dan*_*ran 1 java xml

我有一个XML文件,如下所示:

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<allinfo>
  <filepath>/mnt/sdcard/Audio_Recorder/</filepath>
  <filename>newxml35500.3gp</filename>
  <annotation>
    <file>newxml35500.3gp</file>
    <timestamp>0:05</timestamp>
    <note>uuuouou</note>
  </annotation>
  <filepath>/mnt/sdcard/Audio_Recorder/</filepath>
  <filename>newxml35501.3gp</filename>
  <annotation>
    <file>newxml35501.3gp</file>
    <timestamp>0:04</timestamp>
    <note>tyty</note>
  </annotation>
</allinfo>
Run Code Online (Sandbox Code Playgroud)

我正在尝试在创建XML之后向XML添加一个附加注释,因此XML还有一个附加注释:

<annotation>
  <file>blah</file>
  <timestamp>0:00</timestamp>
  <note>this is a note</note>
</annotation>
Run Code Online (Sandbox Code Playgroud)

找到根然后在Java中用XML写几行的最佳方法是什么?我已经看到DocumentBuilderFactory从其他人那里获得了一些用处,但我不确定如何正确实现它.任何帮助将非常感激.

Pau*_*zie 5

这有效:

    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    final Document document = documentBuilder.parse(new ByteArrayInputStream("<foo><bar/></foo>".getBytes("UTF-8")));
    final Element documentElement = document.getDocumentElement();
    documentElement.appendChild(document.createElement("baz"));
Run Code Online (Sandbox Code Playgroud)

你会得到:

<foo><bar/><baz/></foo>
Run Code Online (Sandbox Code Playgroud)