开发者

Adding node value to xhtml using DOM with java

开发者 https://www.devze.com 2023-04-05 02:43 出处:网络
I have a requirement, that i want to add body content inside th开发者_Python百科e xhtml file. I have a xhtml file with empty body tag. So, i want to add the body content through java using parsers, So

I have a requirement, that i want to add body content inside th开发者_Python百科e xhtml file. I have a xhtml file with empty body tag. So, i want to add the body content through java using parsers, So I am doing some thing like below , but its not working..

Can anyone tell the cause

org.w3c.dom.Document document=null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
document = factory.newDocumentBuilder().parse(newFile);
NodeList list =document.getElementsByTagName("body");               
for (int i = 0; i < list.getLength(); i++) {                    
Node addBody = list.item(i);

addBody.setTextContent(bodyContent.toString());
System.out.println("text content"+addBody.getTextContent());
}

in the bodyContent i have some info which i want to append inside body of newFile. Even i used the method setNodeValue(), it's also not working for me. Any thing is wrong?

I'm getting the addBody value as '[body: null]'; how to point to that body node?

Please give me any pointers..

Thanks in advance..


When you modify the dom tree, you modify it in memory, but the original file where this dom tree comes from is not affected. You need to write the modified dom tree to the file in order to persist the changes you have made in memory.

It's exactly the same as if you read a whole file in a StringBuilder. Modifying the StringBuilder won't magically write the new content to the file.

See http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html for example code to write a DOM tree to a file.


Node value? did you mean Text Node? If that, you shoud create a new text node and append it to addBody. You can just call setNodeValue in a TextNode object to set the text content. Please check http://download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Document.html#createTextNode%28java.lang.String%29

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号