File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes XML and Related Technologies and the fly likes XML parsing with dom Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "XML parsing with dom" Watch "XML parsing with dom" New topic

XML parsing with dom

sanjeev kumar mandal

Joined: Nov 26, 2007
Posts: 23
Hi All,

I am new to xml parsing and i have written a java program to dynamically add element to an existing xml. But the program is not adding element. Please any body correct me if i have done any mistake in the code .

I am sending the sample xml and java code below. code below====

DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse("C:/DspaceAndMoodleProject/workspace/vocab/srsc.xml");
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("node");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {

Element el = (Element)nl.item(i);

if(el.getAttribute("label").equalsIgnoreCase("Church studies")){
System.out.println(" print label : " +el.getAttribute("label"));
System.out.println(" print id : " +el.getAttribute("id"));
Element createIsComposedByTag = dom.createElement("isComposedBy");
Element newNodeTag = dom.createElement("node");
newNodeTag.setAttribute("id", "0099019");
newNodeTag.setAttribute("label", "lecture on cristionity");
Element newHasNote = dom.createElement("hasNote");
newHasNote.setNodeValue("value shilong");

// end of java code

//==== srsc.xml file===

<?xml version="1.0" encoding="UTF-8"?>
<node id="ResearchSubjectCategories" label="Research Subject Categories">
<node id="SCB11" label="HUMANITIES and RELIGION">

<node id="VR110103" label="Church studies">
<node id="VR110105" label="Systematic theology">
<hasNote>Systematisk teologi</hasNote>

<node id="VR110106" label="Islamology">

<node id="SCB15" label="socisl science">

<node id="VR11016" label="socisl studies">
<node id="VR1107" label="socisl abc">

<node id="VR118" label="magnetism">
<hasNote>social studies by mit</hasNote>

<hasNote>Research stusies</hasNote>
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
But the program is not adding element.

You may have changed the DOM in memory but the original document file will be unchanged unless you write the new DOM over it.

Using the code tags would make it a lot easier to read your post.

I agree. Here's the link:
subject: XML parsing with dom
It's not a secret anymore!