2011-07-22 23 views
1

我有一個看起來像這樣的XML文件:Java - 如何將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有一個額外的:

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

什麼是找到根並在Java中寫入幾行到XML的最佳方法?我已經看到DocumentBuilderFactory從別人那裏獲得一些用途,但我不確定如何正確實現它。任何幫助將非常感激。

+0

我不會推薦添加一個屬性到以<?開頭的<?xml行標籤。被稱爲指令,對解析器有特殊意義。將它放在您的標籤中會更有意義。即

+0

@dancran:你到目前爲止嘗試過什麼?大量的例子在那裏... – home

+0

orginial XML文件是使用XMLSerializer和OutputStream編寫的,但我沒有看到如何使用它來重新打開相同的XML,找到我想寫的地方,然後寫入連接關閉到文件後的更多信息。因此,爲什麼我正在尋找另一種方式來打開與XML文件的連接並添加其他信息 – dancran

回答

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> 
+0

有用的答案。爲了讓它更有幫助,您可以提供一個指向DocumentBuilder的JavaDoc的鏈接? – LarsH

+0

@paul mckenzie看起來不錯,但我有一個問題。我看不出它是如何知道寫入保存的XML文件的。難道我不需要在某處傳遞一個路徑,所以它知道在哪裏解析和輸入? – dancran

+0

使用javax.xml.transform.Transformer將文檔轉換爲字符串,然後將字符串寫入文件。 –

0

加載該文件內容爲一個字符串,並使用正則表達式和字符串操作執行插入。

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(); 
} 
相關問題