0

I am receiving a xml payload from a web service call and it is assigned in a String. This xml has 10 elements and I need to change the value of logtime to whatever I want. Since this is a String, is there a way to change any of the element's value.

This is my first java code please let me know if you need more explanation.

code

String xml = dto.getAuditTrail();

Xml

enter image description here

I want to know how can I suppose change the time value of logtime to another format, since this entire xml is a String?

Please help because I am new to it.

Thanks

Mike
  • 777
  • 3
  • 16
  • 41

1 Answers1

0

You need to parse your String in order to obtain a Document object which you can read by tag.

Here you can find how to parse your string, then with Document object you're able to read specific tag:

public void readDocument(Document doc) {
    try{
        NodeList nList = doc.getElementsByTagName("Event");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("LogTime : " + eElement.getElementsByTagName("logTime").item(0).getTextContent());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Source here

This is basic way for xml reading, but you can directly edit the xml too:

public void editDocument() {
    try{
        NodeList nList = doc.getElementsByTagName("Event");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                Node logTimeNode = eElement.getElementsByTagName("logTime").item(0);
                String logTimeString = logTimeNode.getTextContent();
                // Do some stuff with logTimeString
                logTimeNode.setTextContent(logTimeString);
            }
        }
        // write the content into xml file
        String filepath = "/path/to/file.xml";
        TransformerFactory transformerFactory = TransformerFactory
        .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Christian Ascone
  • 1,117
  • 8
  • 14