import java.io.File
import java.io.FileWriter
import org.dom4j.Document
import org.dom4j.Element
import org.dom4j.io.OutputFormat
import org.dom4j.io.SAXReader
import org.dom4j.io.XMLWriter
public class ModifyXML
{
public static void main ( String[] args )
{
Document document = null
SAXReader saxReader = null
XMLWriter xmlWriter = null
File file = null
FileWriter fw = null
OutputFormat outFmt = null
try
{
file = new File ("test_3.xml")
saxReader = new SAXReader ()
document = saxReader.read (file)
Element root = document.getRootElement ()
Element fc = (Element) root.elements ().get (0)
Element cloned = (Element) fc.clone ()
cloned.addAttribute ("hello", "world")
root.add (cloned)
outFmt = new OutputFormat (" ", true)
outFmt.setEncoding ("UTF-8")
fw = new FileWriter (file)
xmlWriter = new XMLWriter (fw, outFmt)
xmlWriter.write (document)
fw.flush ()
xmlWriter.flush ()
xmlWriter.close ()
fw.close ()
}
catch (Exception e)
{
e.printStackTrace ()
}
}
}
dom4j中,使用Element.attributes方法可以获取到节点的属性,而使用elements则可以获取相应的子节点比如:
Element root = doc.getRootElement()
List attrList = root.attributes()
for (int i = 0i <attrList.size()i++) {
//属性的取得
Attribute item = (Attribute)attrList.get(i)
System.out.println(item.getName() + "=" + item.getValue())
}
List childList = root.elements()
for (int i = 0i <childList.size()i++) {
//子节点的操作
Element it = (Element) childList.get(i)
//对子节点进行其它操作...
}