fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import org.w3c.dom.*;
  7. import javax.xml.parsers.*;
  8. import org.xml.sax.*;
  9. import javax.xml.namespace.NamespaceContext;
  10. import javax.xml.xpath.*;
  11. import javax.xml.transform.*;
  12. import javax.xml.transform.stream.*;
  13. import javax.xml.transform.dom.*;
  14.  
  15.  
  16. /* Name of the class has to be "Main" only if the class is public. */
  17. class Ideone
  18. {
  19. public static void main (String[] args) throws java.lang.Exception
  20. {
  21. String str = " <driver>\n"
  22. + " <BirthDate>1977-07-18</BirthDate>\n"
  23. + " <Age>40</Age> \n"
  24. + " <Gender>M</Gender>\n"
  25. + " <PrimaryResidence>OwnCondo</PrimaryResidence>\n"
  26. + " </driver> ";
  27. String output = changeCoreDiscountType(str);
  28. System.out.println(output);
  29. }
  30.  
  31.  
  32.  
  33. public static String changeCoreDiscountType(String reqXML) {
  34. Document document = null;
  35. String updatedXML = null;
  36. try {
  37. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  38. DocumentBuilder builder = factory.newDocumentBuilder();
  39. InputSource is = new InputSource();
  40. is.setCharacterStream(new StringReader(reqXML));
  41. document = builder.parse(is);
  42.  
  43. XPath xPath = XPathFactory.newInstance().newXPath();
  44. XPathExpression expression = xPath.compile("/driver/Gender | /driver/PrimaryResidence");
  45. NodeList nodeList = (NodeList) expression.evaluate(document,XPathConstants.NODESET);
  46.  
  47. for(int i = 0; i < nodeList.getLength(); i++) {
  48. Node node = nodeList.item(i);
  49. System.out.println(node.getNodeName());
  50. if(node.getNodeName() == "Gender")
  51. node.setTextContent("F");
  52. if(node.getNodeName() == "PrimaryResidence")
  53. node.setTextContent("OwnCondox");
  54. }
  55.  
  56. TransformerFactory transformerFactory = TransformerFactory.newInstance();
  57. Transformer transformer = transformerFactory.newTransformer();
  58. DOMSource source = new DOMSource(document);
  59. StreamResult result = new StreamResult(new StringWriter());
  60. transformer.transform(source, result);
  61.  
  62. updatedXML = result.getWriter().toString();
  63. } catch (Exception ex) {
  64. ex.printStackTrace();
  65. }
  66. return updatedXML;
  67. }
  68. }
Success #stdin #stdout 0.18s 2184192KB
stdin
Standard input is empty
stdout
Gender
PrimaryResidence
<?xml version="1.0" encoding="UTF-8" standalone="no"?><driver>
    <BirthDate>1977-07-18</BirthDate>
    <Age>40</Age>                    
    <Gender>F</Gender>
    <PrimaryResidence>OwnCondox</PrimaryResidence>
 </driver>