I am consider an example from here: http://www.rgagnon.com/javadetails/java-0625.html
We have an XML file:
<data>
<employee>
<name>John</name>
<title>Manager</title>
</employee>
<employee>
<name>Sara</name>
<title>Clerk</title>
</employee>
</data>
We use this Java app:
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XMLReplaceDemo {
static String inputFile = "C:/temp/data.xml";
static String outputFile = "C:/temp/data_new.xml";
public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new InputSource(inputFile));
// locate the node(s)
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate
("//employee/name[text()='John']", doc, XPathConstants.NODESET);
// make the change
for (int idx = 0; idx < nodes.getLength(); idx++) {
nodes.item(idx).setTextContent("John Paul");
}
// save the result
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(outputFile)));
}
}
to change <name>John</name>
to <name>John Paul</name>
.
The example works perfectly for Latin symbols, digits, punctuation marks, but it returns a bunch of unreadable characters if I attempt to replace the original value with the one written in cyrillic symbols.
So the question is: is there any way to modify the Java code to make it work as I need it to?
I am a novice in Java.