• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inserting this element into an xml file using java?

 
Sean Michael Hayes
Ranch Hand
Posts: 54
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How are you reading and writing the file right now? Which API do you use?
 
Sean Michael Hayes
Ranch Hand
Posts: 54
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 20983
31
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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! :)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic