File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes XML and Related Technologies and the fly likes Inserting this element into an xml file using java? 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 "Inserting this element into an xml file using java?" Watch "Inserting this element into an xml file using java?" New topic
Author

Inserting this element into an xml file using java?

Sean Michael Hayes
Ranch Hand

Joined: Feb 08, 2012
Posts: 54

I have this xml file



What I want to do is get a new <reading> element with its children (I know how to create one) and insert it at the end of the <readings> element after the last child of <readings>

But the problem is that it needs to be inserted in to a specific device based on its <name> element value, not all of them. How would I do this with the way the file is written now?
I understand if the file is not written in the best way to allow this but modifying how the file is written would require re-doing a lot of my java code so if it is possible I would rather go ahead with that.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2376
    
  28

How are you reading and writing the file right now? Which API do you use?
Sean Michael Hayes
Ranch Hand

Joined: Feb 08, 2012
Posts: 54

Jayesh A Lalwani wrote:How are you reading and writing the file right now? Which API do you use?



I am using SAX to parse the XML file. Up to now I have only been reading from the XML file, I have not written anything to it yet.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

What I would recommend is this:

1. Use DOM to parse the file and build a Document object.

2. Use XPath to find the element into which you want to insert your newly-built element.

3. Insert the newly-built element into the element you just found.

4. Write the Document out to a new file using a Transformer.
Sean Michael Hayes
Ranch Hand

Joined: Feb 08, 2012
Posts: 54

Paul Clapham wrote:What I would recommend is this:

1. Use DOM to parse the file and build a Document object.

2. Use XPath to find the element into which you want to insert your newly-built element.

3. Insert the newly-built element into the element you just found.

4. Write the Document out to a new file using a Transformer.


I'll certainly give that a try! Thank you very much! :)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inserting this element into an xml file using java?