0

I have the following method:

    public String processMessage(String xml) throws RemoteException {

        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document document = dBuilder.newDocument();
            document = dBuilder.parse(new InputSource(new StringReader(xml)));
            NodeList entries = document.getElementsByTagName("*"); // TO GET NODE NAMES
            
            System.out.println(document.getElementsByTagName("NODE_NAME").item(0).getTextContent());

        }
    }

Is there a more optimal way of accessing node names and actual values? The way I have it now works, I just feel like there should be a better way of doing it.

EDIT:

<ow-e:Envelope revision="2.0" xmlns:ow-e="http://www.url.com/test-envelope">
   <ow-e:Header>
      <ow-e:EndPoints>
         <ow-e:To>
            <ow-e:Id>123</ow-e:Id>
         </ow-e:To>
         <ow-e:From>
            <ow-e:Id>321</ow-e:Id>
         </ow-e:From>
      </ow-e:EndPoints>
      <ow-e:Properties>
         <ow-e:Identity>123</ow-e:Identity>
         <ow-e:SentAt>2003-03-25T12:00:00</ow-e:SentAt>
         <ow-e:Topic>test</ow-e:Topic>
      </ow-e:Properties>
   </ow-e:Header>
</ow-e:Envelope>
A.J
  • 1,140
  • 5
  • 23
  • 58
  • 1
    What do you understand by "more optimal"? More efficient, more readable, easier to maintain or change in the future, etc? You tagged your question SOAP. Is the XML you are parsing a SOAP message? A better approach would be to use SOAP libraries or frameworks to read the message instead of doing it by traversing the XML document, but again, that depends on your definition of optimal. – Bogdan Apr 26 '21 at 14:28
  • @Bogdan Yes it is a SAOP message. Similar to my edit. By optimal I mean all of the above. I am aware that my method is not ideal, at best. – A.J Apr 26 '21 at 14:43
  • 1
    I provided an answer to this [other question](https://stackoverflow.com/questions/67269010/writing-an-xml-soap-message-in-java) of yours. If neither JAXB or SAAJ are an option, then working with XML libraries from the JDK is your best bet. Just make sure you understand how to properly format SOAP messages (structure + namespaces) – Bogdan Apr 26 '21 at 15:39
  • @Bogdan yep I replied to your comment there. – A.J Apr 27 '21 at 16:37

0 Answers0