コード test.xml を試してください
<?xml version="1.0"?>
<root>
<alerts>
<fullName>email_alert_campaign</fullName>
<description>email alert campaign</description>
<recipients>
<recipient>abc_puv@xyz.com</recipient>
<type>user</type>
</recipients>
<senderType>CurrentUser</senderType>
</alerts>
<tasks>
<fullName>Task_on_completing_a_campaign</fullName>
<assignedTo>abc_puv@xyz.com</assignedTo>
<subject>Task on completing a campaign</subject>
</tasks>
</root>
public class XMLParsing {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
File fXmlFile = new File("D:/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
// optional, but recommended
// read this -
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath
.compile("//assignedTo");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
System.out.println("Root element :"
+ node.getTextContent());
node.setTextContent("abc_puv@efg.com");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
}
}