Java equivalent of System.Xml.XmlNode.InnerXml
Is there a java equivalent of .NET's System.Xml.XmlNode.InnerXml
?开发者_开发百科
I need to replace some words in an XML document.
I cannot use Java's org.w3c.dom.Node.setTextContent()
because this removes the XML nodes.
Thanks!
Source:
<body>
<title>Home Owners Agreement</title>
<p>The <b>good</b> thing about a Home Owners Agreement is that...</p>
</body>
Desired output:
<body>
<title>Home Owners Agreement</title>
<p>The <b>good</b> thing about a HOA is that...</p>
</body>
I only want text in <p>
tags to be replaced. I tried the following:
replaceText(string term, string replaceWith, org.w3c.dom.Node p){
p.setTextContent(p.getTextContent().replace(term, replaceWith));
}
The problem with the above code is that all the child nodes of p
get lost.
You could have a look at jdom.
Something like document.getRootElement().getChild("ELEMENT1").setText("replacement text");
You have a little bit of work to do in converting the document into a JDOM document, but there are adapters that make that fairly easy for you. Or, if the XML is in a file, you can just use a JDOM Builder class to create the DOM that you want to manipulate. `
Okay, I figured out the solution.
The key to this is that you don't want to replace the text of the actual node. There is a actually a child representation of just the text. I was able to accomplish what I needed with this code:
private static void replace(Node root){
if (root.getNodeType() == root.TEXT_NODE){
root.setTextContent(root.getTextContent().replace("Home Owners Agreement", "HMO"));
}
for (int i = 0; i < root.getChildNodes().getLength(); i++){
outputTextOfNode(root.getChildNodes().item(i));
}
}
精彩评论