On Wed, Jun 05, 2002 at 09:27:49PM +0000, Jason Lee wrote:
> I need to insert an element in an exisiting xml doc
> <parent>
> <child name="attr">
> --- (need to insert another child here)
> </>
>
> I tried to take some help from this list regarding the same question..
> but I was not succesfull in updating the XML document..can anyone suggest me
> a sample code...
The attached source creates a child of the root element, and mutates some
first-level children. I also attached an XML file that matches my code.
Hope this helps!
--
Miguel A Paraz <http://mparaz.com> Mobile: +63-916-423-7922
Imperium Technology, Inc. <[EMAIL PROTECTED]> Office: +63-2-812-3155
import java.io.File;
import java.net.MalformedURLException;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
/*
* read in the journal with SAX, then add a new element containing the count.
* mutates text entries to add a "type" attribute.
*/
public class DemoDom4jMutate2 {
public static Document readDocument(File aFile) throws DocumentException,
MalformedURLException {
SAXReader xmlReader = new SAXReader();
return xmlReader.read(aFile);
}
public static void main(String[] args) {
XMLWriter xmlWriter;
Document document;
OutputFormat outputFormat;
Element rootElement;
Iterator rootIterator;
int pinoyjugCounter = 0;
// Read in
try {
document = readDocument(new File(args[0]));
}
catch (Exception e) {
e.printStackTrace();
return;
}
// Mutate. Let dom4j do the matching.
rootElement = document.getRootElement();
rootIterator = rootElement.elementIterator("entry");
while (rootIterator.hasNext()) {
Element e = (Element)rootIterator.next();
// System.out.println(e);
// Level 2. Get the text entries.
Iterator l2Iterator = e.elementIterator("text");
// Mutate
while (l2Iterator.hasNext()) {
e = (Element)l2Iterator.next();
// System.out.println(" " + e.toString());
e.addAttribute("type", "1");
pinoyjugCounter++;
}
}
// Append the result
rootElement.addElement("pinoyjug").addText("" + pinoyjugCounter);
// Pretty-print
outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
try {
xmlWriter = new XMLWriter(System.out, outputFormat);
}
catch (java.io.UnsupportedEncodingException e) {
System.out.println(e);
return;
}
try {
xmlWriter.write(document);
xmlWriter.flush();
}
catch (java.io.IOException e) {
System.out.println(e);
return;
}
System.out.println("");
}
}
<?xml version="1.0"?>
<series xmlns="http://mparaz.com/xml/journal"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://mparaz.com/xml/journal journal.xsd">
<entry>
<date>May 19, 2002</date>
<text>
Sample text. We should support some markup here.
</text>
</entry>
<entry>
<date>May 19, 2002 10:27</date>
<text>
Second batch.
</text>
</entry>
</series>