2012-08-23 197 views
0

好吧,我正在研究計算某些內容的程序,然後將該數據添加到同一目錄中的現有XML文件。我已經使用DocumentBuilder解析文件,現在需要(至少這是我認爲我需要做的,請改正我,我錯了)從parsered文件中獲取元素,並將appendChild另一個元素添加到它。使用parsered Java DOM XML中的元素添加新元素

這裏是到目前爲止的代碼 進口包:

import java.applet.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import java.text.*; 
import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamSource; 

和功能,實際上解析器和編輯XML文件:當我嘗試在這裏編譯這段代碼

public void saveIt(){ 
     DocumentBuilder bd = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = bd.parse("excersize.xml"); 
     Element root = doc.getElementsByTagName("root"); 
     Element today = doc.createElement(today); 
     root.appendChild(today); 
    } 

我得到的錯誤(fyi,這是一個定製的cmd):

Good Luck Sir: javac excersize.java 
excersize.java:240: error: incompatible types 
       Element root = doc.getElementsByTagName("root"); 
                ^
    required: Element 
    found: NodeList 
excersize.java:241: error: method createElement in interface Document cannot be 
applied to given types; 
       Element today = doc.createElement(today); 
           ^
    required: String 
    found: Element 
    reason: actual argument Element cannot be converted to String by method invoca 
tion conversion 
2 errors 

回答

1

方法doc.getElementsByTagName("root")返回NodeList即可更改,

Element root = doc.getDocumentElement();