Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need to edit XML file

 
Prabhat Gupta
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I am very new to XML and DOM . I need to edit a xml file which has following contents

<?xml version="1.0" encoding="UTF-8"?>
<DAOServices>
<DAOService name="default">
<SimpleDMDBStrategy name="default">
<URL>jdbcracle:thin:@100.101.02.03:1521:TIGER</URL>
<UserName>USER1</UserName>
<Password>PASSWORD1</Password>
<DriverName>oracle.jdbc.driver.OracleDriver</DriverName>
</SimpleDMDBStrategy>
</DAOService>
</DAOServices>

here i wish to change the value of UserName to USER2 and similarly value of Password to PASSWORD2 as below

<?xml version="1.0" encoding="UTF-8"?>
<DAOServices>
<DAOService name="default">
<SimpleDMDBStrategy name="default">
<URL>jdbcracle:thin:@100.101.02.03:1521:TIGER</URL>
<UserName>USER2</UserName>
<Password>PASSWORD2</Password>
<DriverName>oracle.jdbc.driver.OracleDriver</DriverName>
</SimpleDMDBStrategy>
</DAOService>
</DAOServices>


Here i found package org.w3c.dom very uncomfortable..at the same time i came to know JDOM is now almost obsolete. During my attempt i faced problem
saying class cast exception com.sun.org.apache.xerces.internal.dom.DeferredTextImpl...

Please suggest me approach to tackle such type of problem.
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Prbahat,

Any limitations to use JAXP DOM ? except if your XML is too large.
1) You can search the element by getElementsByTagName
2) Then change the node value by creating new element
Element newNode = document.createElement("userName");
newNode.setTextContent(""); // new Node value ;
3) replace this element in the XML parent element
4) Write the changed DOM to a new XML or overwrite to same xml.
using Transformer object transform method.
 
Prabhat Gupta
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a ton Balu
A very simple but effective approach.
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You are welcome. I'm glad that you picked up from the pseudocode.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic