• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Change XML element using Java

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Megha Patni
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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>
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 2856
10
Firefox Browser Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"venkatesan welcome" please check your private messages for an important administrative matter. You can see them by clicking the My Private Messages link above.
 
venkatesan welcome
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...
 
reply
    Bookmark Topic Watch Topic
  • New Topic