Sushan Ghimire
Sushan Ghimire

Reputation: 7567

How to append element in a XML file using dom?

My XML file looks like this:

<Messages>
    <Contact Name="Robin" Number="8775454554">
        <Message Date="24 Jan 2012" Time="04:04">this is report1</Message>
    </Contact>
    <Contact Name="Tobin" Number="546456456">
        <Message Date="24 Jan 2012" Time="04:04">this is report2</Message>
    </Contact>
<Messages>

I need to check whether the 'Number' attribute of Contact element is equal to 'somenumber' and if it is, I'm required to insert one more Message element inside Contact element.

How can it be achieved using DOM? And what are the drawbacks of using DOM?

Upvotes: 2

Views: 5611

Answers (5)

Lukas Eder
Lukas Eder

Reputation: 220787

DOM has two main disadvantages:

  • It requires reading of the complete XML into a Java representation in memory. That can be both time and memory consuming
  • It is a pretty verbose API, so you need to write a lot of code to achieve simple things like you're asking for.

If time and memory consumption is OK for you, but verbosity is not, you could still use jOOX, a library that I have created to wrap standard Java DOM objects to simplify manipulation of XML. These are some examples of how you would implement your requirement with jOOX:

// With css-style selectors
String result1 = $(file).find("Contact[Number=somenumber]").append(
  $("<Message Date=\"25 Jan 2012\" Time=\"23:44\">this is report2</Message>")
).toString();

// With XPath
String result2 = $(file).find("//Contact[@Number = somenumber]").append(
  $("<Message Date=\"25 Jan 2012\" Time=\"23:44\">this is report2</Message>")
).toString();

// Instead of file, you can also provide your source XML in various other forms

Note that jOOX only wraps standard Java DOM. The underlying operations (find() and append(), as well as $() actually perform various DOM operations).

Upvotes: 2

Kingamajick
Kingamajick

Reputation: 2281

The main drawback to using a DOM is it's necessary to load the whole model into memory at once, rather than if your simply parsing the document, you can limit the data you keep in memory at one point. This of course isn't really an issue until your processing very large XML documents.

As for the processing side of things, something like the following should work:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(is);
NodeList contacts = dom.getElementsByTagName("Contact");
for(int i = 0; i < contacts.getLength(); i++) {
    Element contact = (Element) contacts.item(i);
    String contactNumber = contact.getAttribute("Number");
    if(contactNumber.equals(somenumber)) {
        Element newMessage = dom.createElement("Message");
        // Configure the message element
        contact.appendChild(newMessage);
    }
}

Upvotes: 5

kafrlust
kafrlust

Reputation: 309

You might want to take a look at this tutorial its about exactly what you want to do

Upvotes: 0

Rajesh Pantula
Rajesh Pantula

Reputation: 10241

Use the Element class to create a new element

Element message = doc.createElement("Message");
message.setAttribute("message", strMessage);

Now add this element after whatever element you want using

elem.getParentNode().insertBefore(message, elem.getNextSibling());

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89169

You will do something to this effect.

  • Get the NodeList of Contact element.
  • Iterate through the NodeList and get Contact element.
  • Get Number through contact.getAttribute("Number") where contact is of type Element.
  • If your number equals someNumber, then add Message by calling contact.appendChild(). Message must be an element.

Upvotes: 1

Related Questions