This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes XML and Related Technologies and the fly likes Change XML element using Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Change XML element using Java" Watch "Change XML element using Java" New topic
Author

Change XML element using Java

Megha Patni
Greenhorn

Joined: Jun 30, 2008
Posts: 6
Hi,

I have the following type of xml.
<formData>
<AccessClient>
<AccessClientID_FIELD></AccessClientID_FIELD>
<RequestType>
<ACHModuleMaint_CHECK>off</ACHModuleMaint_CHECK>
<Change_ABA>
<Change_ABA_CHECK>off</Change_ABA_CHECK>
</Change_ABA>
<AccNumsDelete>
<AccNumDel1_POPUP></AccNumDel1_POPUP>
</AccNumsDelete>
</RequestType>
</AccessClient>
</formData>

I want to create an xml of the below format.

<formData>
<AccessClient>
<AccessClientID></AccessClientID>
<RequestType>
<ACHModuleMaint>off</ACHModuleMaint>
<Change_ABA>
<Change_ABAoff</Change_ABA>
</Change_ABA>
<AccNumsDelete>
<AccNumDel1></AccNumDel1>
</AccNumsDelete>
</RequestType>
</AccessClient>
</formData>

ie. I want to remove all the _CHECK, _POPUP and _FIELD from the xml. Can anyone help me to do it in JAVA using XPATH/DOMParser?

Thanks in advance,
Megha
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12676
    
    5
Can anyone help me to do it in JAVA using XPATH/DOMParser?


I would certainly NOT use XPath or a DOM approach. This looks ideal for a simple XSLT transform since you are only changing names, not the structure. I am sure an XSLT expert could handle this quickly but I dont qualify.

Bill


Java Resources at www.wbrogden.com
Megha Patni
Greenhorn

Joined: Jun 30, 2008
Posts: 6
Thanks for the reply Bill. I have never worked on XSLT so I donot know how to code using it. It would be great if someone help me out using XPATH/DOMParser.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18124
    
    8

I would use XSLT as well. I find working with DOM a painful experience. However, whatever you eventually choose to do, let me point out that (based on your example) you do not want to just delete the elements whose names end in "_CHECK". In one case you rename that element to have the same name with "_CHECK" removed. In another case you take the text child node of the element and move it up to be the text child node of the element's parent, deleting the existing text children of the parent.

Perhaps your DOM code wasn't working out because your requirement description didn't match up with the actual requirement?
Megha Patni
Greenhorn

Joined: Jun 30, 2008
Posts: 6
All I want to do is to remove all the _CHECK, _FIELD and _POPUP from the new xml. I have never worked on XSLT so I need to program using XPATH or DOMParser or SAXParser.
Please help me for it.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18124
    
    8

Well, that's not what your example showed, but let's do that anyway. What code have you got so far? What part of deleting the elements from the DOM are you having trouble with?
Megha Patni
Greenhorn

Joined: Jun 30, 2008
Posts: 6
Hi Paul,

Through google I have found some code for replacement and I have modified it for my code. But the google code was giving error so I am stuck at it.
Following is the code I have written so far.

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.DOMBuilder;
import org.jdom.output.XMLOutputter;

// used for printing
import org.apache.xml.serialize.XMLSerializer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

class XMLWriter
{

public void update(File fileName)
{
try
{
DOMBuilder domBuilder = new DOMBuilder();
Document doc = domBuilder.build(fileName);//gives error here as build method is for Document type.

Element element = doc.getRootElement();
getChildren(element);

writeToXML(doc, fileName);
getChildren(element);

}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* @param doc
*/
private void writeToXML(Document document, File filePath)
{
XMLOutputter xmloutputter = new XMLOutputter();
try
{
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
xmloutputter.output(document, fileOutputStream);
fileOutputStream.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}

}

public void getChildren(Element element)
{

List childrenList = element.getChildren();
Iterator itr = childrenList.iterator();

while (itr.hasNext())
{
Element childElement = (Element) itr.next();
String fieldElement = (String) itr.next();
if (childElement.getChildren() != null)
{
getChildren(childElement);
}

//replace _FIELD
if (childElement.getName().contains("_FIELD"))
{
int occurance = fieldElement.indexOf("_");
fieldElement = fieldElement.substring(0, occurance);
updateInfo(childElement, "fieldElement");
}

//replace _POPUP
if (childElement.getName().contains("_POPUP"))
{
int occurance = fieldElement.indexOf("_");
fieldElement = fieldElement.substring(0, occurance);
updateInfo(childElement, "fieldElement");
}

//replace _CHECK
if (childElement.getName().contains("_CHECK"))
{
int occurance = fieldElement.indexOf("_");
fieldElement = fieldElement.substring(0, occurance);
updateInfo(childElement, "fieldElement");
}
}
}

/**
* @param childElement
* @param string
* @param string2
*/
private void updateInfo(Element element, String elementName)
{
element.setName(elementName);
}

static public void main(String[] args)
{
XMLWriter xmlWriter = new XMLWriter();
xmlWriter.update(new File("c:\\formData.xml"));
}
}

I am getting error in the build method of the domBuilder. Please help me in the above code or suggest some other way.

Thanks in advance,
Megha
Nikos Pougounias
Ranch Hand

Joined: Jan 16, 2008
Posts: 110
Here's another sample solution using dom4j. The renaming occurs on-the-fly while the document is being read. Please see renameNodes() where all "AccessClientID_FIELD" elements are renamed as an example.

<blockquote>code:
<pre name="code" class="java">
import java.io.File;
import java.io.FileWriter;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.ElementHandler;
import org.dom4j.ElementPath;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XMLTransformer {

private Document document;
private String path;

public XMLTransformer(String path) throws Exception {
this.path = path;
load();
}

/**
* Loads the original document.
*/
private void load() throws Exception {
URL url = new File(path).toURI().toURL();
SAXReader reader = new SAXReader();
renameNodes(reader);
document = reader.read(url);
}

/**
* Renames some nodes while they are being parsed.
*/
private void renameNodes(SAXReader reader) {
reader.addHandler("/formData/AccessClient/AccessClientID_FIELD",
new ElementHandler() {
public void onStart(ElementPath path) {
}

public void onEnd(ElementPath path) {
Element row = path.getCurrent();
row.setName("AccessClientID");
}
});
}

/**
* Returns the updated document.
*/
public Document getDocument() {
return document;
}

/**
* Saves the updated document to its original location on disk.
*/
public void save() throws Exception {
XMLWriter writer = new XMLWriter(new FileWriter(path));
writer.write(document);
writer.close();
}

public static void main(String[] args) throws Exception {
new XMLTransformer("C:/megha.xml").save();
}

}
</pre>
</blockquote>


Nikos' Java blog
venkatesan welcome
Greenhorn

Joined: Dec 26, 2008
Posts: 2
hi
i need update particular node text value using java
example:
this is my original coding;
<?xml version="1.0" encoding="UTF-8"?>
<Communication>
<CartId>2224</CartId>
<Type>true</Type>
<callFlag>iStore</callFlag>
</Communication>

i need update type node value

<?xml version="1.0" encoding="UTF-8"?>
<Communication>
<CartId>2224</CartId>
<Type>false</Type>
<callFlag>iStore</callFlag>
</Communication>

thanks
welcome
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2712
    
    5

"venkatesan welcome" please check your private messages for an important administrative matter. You can see them by clicking the My Private Messages link above.


SCJP, SCWCD.
|Asking Good Questions|
venkatesan welcome
Greenhorn

Joined: Dec 26, 2008
Posts: 2
hi
i need to update or change particular value for example my xml file
<?xml version="1.0" encoding="UTF-8"?>
<RootElement>
<callflag>False</callflag>
<RootElement>

i need update this tag value
<callflag>False</callflag> to <callflag>true</callflag> using java coding i am using sax parser in that i have used setNodeValue and then i use getNodeValue method at that i retrieved thus the updated value but the xml file was not updated
<?xml version="1.0" encoding="UTF-8"?>
<RootElement>
<callflag>False</callflag>
<RootElement>

i need java coding for update the xml tag value please reply soon.

thanks
new
Saurabh Gangarde
Greenhorn

Joined: Jun 06, 2008
Posts: 10
Hi I have been trying to parse this xml file a little bit of code I am putting here....

What I want is just get the value of "movie_folder" when I want....
Please show mw some direction on how to do that...?
Thanks in advance...
I hope I am not interrupting other thread members...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Change XML element using Java
 
Similar Threads
Navigation of XML records
Parsing XML with JAXP
storing a XML parsed value's
XSLT and Internet Explorer problem
Send and Receive Binary Data in XML