Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append element in a XML file using dom?

Tags:

java

dom

xml

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?

like image 281
Sushan Ghimire Avatar asked Jan 24 '26 06:01

Sushan Ghimire


1 Answers

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);
    }
}
like image 100
Kingamajick Avatar answered Jan 25 '26 18:01

Kingamajick