I have an xml file input.xml as below:
<?xml version='1.0' encoding='UTF-8'?> <parameter name=""name""> <summary>"summary"</summary> <username>leon</username> </parameter>
And I use dom4j library to parse the xml file to add email address postfix "@sa.com" to useranme element value:
import org.dom4j.*; import org.dom4j.io.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { SAXReader reader = new SAXReader(); InputStream in = new FileInputStream("input.xml"); Document doc = reader.read(in); Element element = (Element) doc.selectSingleNode("/parameter/username"); element.setText(element.getText() + "@sa.com"); StringWriter writer = new StringWriter(); writer.write(doc.asXML()); System.out.println("Converted Xml is:\n" + writer.toString()); } }
After running the code, I get below result:
Converted Xml is: <?xml version="1.0" encoding="UTF-8"?> <parameter name=""name""> <summary>"summary"</summary> <username>leon@sa.com</username> </parameter>
From the result, you can see the summary element value changes from
<summary>"summary"</summary>
to
<summary>"summary"</summary>
But the name attribute value which contains entity reference character doesn't change.
Why is it working like this? If I want to retain the original summary element value <summary>"summary"</summary>, how should I achieve that?