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

时间:2011-07-22 14:03:17

标签: 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>

我正在尝试在创建XML之后向XML添加一个附加注释,以便XML有一个额外的注释:

<annotation>
  <file>blah</file>
  <timestamp>0:00</timestamp>
  <note>this is a note</note>
</annotation>

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

2 个答案:

答案 0 :(得分: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"));

你会得到:

<foo><bar/><baz/></foo>

答案 1 :(得分:0)

将文件内容加载到String中,并使用Regex和String操作来执行插入。

String xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
    + "<allinfo>"
    + "<filepath>/mnt/sdcard/Audio_Recorder/</filepath>"
    + "...";
// String xml = loadFromFile();

Pattern p = Pattern.compile("(.*?)(<allinfo>)(.*?)");
Matcher m = p.matcher(xml);

if (m.matches()) {
    StringBuilder bld = new StringBuilder(m.group(1));
    bld.append(m.group(2));
    bld.append("<annotation>").append("\n");
    bld.append("<file>blah</file>").append("\n");
    bld.append("<timestamp>0:00</timestamp>").append("\n");
    bld.append("<note>this is a note</note>").append("\n");
    bld.append("</annotation>").append("\n");
    bld.append("m.group(3));

    xml = bld.toString();
}