How To Retain Entity Reference Character While Reading XML
I have an xml file input.xml as below:
Code Java:
<?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:
Code Java:
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:
Code Java:
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?
Re: How To Retain Entity Reference Character While Reading XML
Hello leon850515.
Welcome to the Java Programming Forums.
The only difference I can see between
<parameter name=""name"">
and
<summary>"summary"</summary>
Is that the first one is in quotes. I'm not sure if this makes a difference?!
Try changing
<summary>"summary"</summary>
to
<summary>""summary""</summary>
and see what happens... This is just a test