Q: How to access and modify xml tags using Java

I have an xml based document that i need to access and change. For example, the code

<section id="section1">

<div>

<xforms:group id="id1">

<xforms:label id="label1">

<l style="font-size:16pt"> something </l>

</xforms:label>

</xforms:group>

</div>

</section>

Working with Java I need to access all the tags, select some of them that are relevant to the current device and remade the document. I thought I would read the file character by character identifying the different labels and building a tree, storing in the tree nodes the relevant information as some kind of attributes (for example, in the case of the <xforms:group id="id1"> I would name the node "xforms:group" and create an "id" attribute with value "id1"). I'm not sure if that is the most efficient way of accessing the problem (computational power might be an issue), and would appreciate some help on the subject.

Thanks,

[1031 byte] By [victorNika] at [2007-11-27 6:14:17]
# 1
hi!I saw this morning some replies here from school, but now that i'm back home and i was going to actually check what they said there's none... how is this possible?
victorNika at 2007-7-12 17:23:41 > top of Java-index,Java Essentials,Java Programming...
# 2

Don't waste your time trying to write code that interprets XML and builds a tree structure out of it. Such code already exists, it's called an XML parser and Java already has one. Read this tutorial to find out how to use it:

http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/dom/index.html

(And hopefully your XML fragment is embedded in a document where the namespaces are declared properly.)

DrClapa at 2007-7-12 17:23:41 > top of Java-index,Java Essentials,Java Programming...
# 3
sometimes when faced with this problem, and needing some stupid quick hack solution i use regex to replace() some text in the file. it is much faster then trying to use a real lib, unless you have a skeleton parser app which i dont.
mkoryaka at 2007-7-12 17:23:41 > top of Java-index,Java Essentials,Java Programming...
# 4

this may help you..

this is a little util i made to help me read/write files.

using this, you are only one step away from your solutions, you only need to figure out the regex you need to run on the text of the file to make it become what you need it to become.

though if you use non-standard encoding, you might not want to use this code..

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Arrays;

public class ASCIIFile {

private File file;

private StringBuilder builder;

public ASCIIFile(String path) throws IOException{

file = new File(path);

openFile();

}

public ASCIIFile(File file) throws IOException{

this.file = file;

openFile();

}

public void setNewFileName(String fileName){

file = new File(file.getAbsolutePath(), fileName);

}

public void setNewFilePath(String filePath){

file = new File(filePath, file.getName());

}

private void openFile() throws IOException{

if(!file.exists()) file.createNewFile();

BufferedReader read = new BufferedReader(new FileReader(file));

String line = read.readLine();

builder = new StringBuilder();

while(line != null){

builder.append(line);

builder.append("\n");

line = read.readLine();

}

read.close();

}

public String getContents(){

return builder.toString();

}

public StringBuilder getStringBuilder(){

return builder;

}

public void setStringBuilder(StringBuilder b) throws IOException{

setContents(b.toString());

}

public void setContents(String contents) throws IOException{

FileWriter writer = new FileWriter(file);

writer.write(contents);

writer.flush();

writer.close();

builder = new StringBuilder(contents);

}

public static File[] getAllFilesUnderDir(String fullpath, boolean recursive) {

ArrayList queue = new ArrayList(10);

ArrayList matched = new ArrayList();

File root = new File(fullpath);

File[] files = root.listFiles();

if (files == null || files.length == 0) {

return new File[] {};

}

queue.addAll(Arrays.asList(files));

for (int j = 0; j < queue.size(); j++) {

File child = (File) queue.get(j);

if (child.isDirectory() && recursive) {

files = child.listFiles();

if (files != null) {

queue.addAll(Arrays.asList(files));

}

} else { // child is file

matched.add(child);

}

}

return (matched.size() > 0)?((File[]) matched.toArray(new File[] {})):(new File[] {});

}

}

mkoryaka at 2007-7-12 17:23:41 > top of Java-index,Java Essentials,Java Programming...
# 5

here, ill throw in another sniplet, this peice of code does some crude "xml parsing", using regex.

public String replaceImgLabel(String total,String newValue){

total = total.replaceAll("\\s+", " ");

Pattern p = Pattern.compile("(?im)(<item name=\"txtbName\">[ ]*<value/>)");

Matcher m = p.matcher(total);

String replace = "<item name=\"txtbName\"><value>"+newValue+"</value>";

if(m.find()){

return total.substring(0, m.start(1))+replace+total.substring(m.end(1));

}

return null;

}

this code finds all occurances of

<item name="txtbName"><value/>

and replaces it with

<item name="txtbName"><value>newValue</value>

though it only works because there is only once occurance (and i know this).

if we had more then one occurance we would need to use appendReplacement() and appendTail() from the matcher class - see api for use, or search my previous posts.

mkoryaka at 2007-7-12 17:23:41 > top of Java-index,Java Essentials,Java Programming...
# 6
Plenty of help! Thanks all, I'll try it all first thing tomorrow. I hope I can manage it (not such a skilled programmer I'm afraid)...
victorNika at 2007-7-12 17:23:41 > top of Java-index,Java Essentials,Java Programming...