Two Laptop Bag*
The moose likes XML and Related Technologies and the fly likes Need to edit XML file 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 "Need to edit XML file" Watch "Need to edit XML file" New topic
Author

Need to edit XML file

Prabhat Gupta
Ranch Hand

Joined: Jan 22, 2008
Posts: 135
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

Joined: Jan 01, 2009
Posts: 874



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

Joined: Jan 22, 2008
Posts: 135
Thanks a ton Balu
A very simple but effective approach.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874


You are welcome. I'm glad that you picked up from the pseudocode.
 
jQuery in Action, 2nd edition
 
subject: Need to edit XML file