Hi DOM-ers
I have a problem with modifying the text component of a node. What I am
hoping to achieve could have the affect of removing emphasis from text,
for example, ie, this xml document:
<myDoc>this is some <emph>emphasis</emph></myDoc>
gets transformed to:
<myDoc>this is some emphasis</myDoc>
The approach which I am using is:
1. Get the text associated with the <emph> node.
2. append it to the text component of the <myDoc> node
3. delete the <emph> node
Using Sun's Java xml-ea2 DOM API
(http://developer.javasoft.com/developer/earlyAccess/xml/index.html),
check out the following code for this purpose. In the example above, the
method copyIntoParent (Node) would be called with <emph> as the
parameter.
The trouble is with the setNodeValue(String) method in the Node
interface of Sun's API. I call it in the setTextInNode(Node n, String
newText) method, but the print outs I have in the copyIntoParent(Node)
method show that it has no affect.
So:
- are there any other DOM-ers using Suns DOM API?
- is setNodeValue(String) the right method to call. if not, what?
Any help/ suggestions will be cool
thanks
N
public void copyIntoParent(Node n) {
// get current node's text content copy it
// into parent node, in place of current node
// Has the affect of removing elements from
// text content.
// Print out the current text value of this node
System.out.println("child " + n.getNodeName() + " " +
getTextFromNode(n));
// update the text value of this node with the "** my new text **"
setTextInNode(n, "** my new text **");
// Print out the updated text value of this node
System.out.println("child " + n.getNodeName() + " " +
getTextFromNode(n));
}
public void setTextInNode(Node n, String newText) {
// Read the text that this node has
// and append to it the new text that is to be added
String currentText = getTextFromNode(n);
currentText += newText;
n.setNodeValue(currentText);
}
public String getTextFromNode(Node n) {
// get current node's text content
Node child;
String textData = "";
NodeList children;
int numberOfChildren;
// If the node has any child nodes,
// bung all of them into a nodelist called children
children = n.getChildNodes();
numberOfChildren = children.getLength();
// Read each child now
for (int i = 0; i < numberOfChildren; i++) {
child = children.item(i);
// If this child has some text, let's get it!
if (child.getNodeType() == 3)
textData += child.getNodeValue();
}
return textData;
}