This code needs to extract data from in XML file. Specifically it needs to iterate over it, looking for a node called CHARGE_CODES that repeats over and over and has several elements. it needs to extract the values of one of them, called CODE. the XML contents are composed of repeating blocks like these:

  <CODE>some value</CODE>
  <OtherElement>some value</Otherelement>

The code then needs to put these values of "CODE" into an array. I create several arrays like these each containing the values of one of these tags.

Then all these arrays are used to send SOAP POSTS and enter together (all elements from one CHARGE_CODES block) into a database as the details of a service.

This code contains one such array collecting the values of one node.

public class Main {
    public static void main(String argv[]){
        String test = "URL";
        File inputFile = new File(test);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputFile);
        NodeList blocks = doc.getElementsByTagName("CHARGE_CODE");
        ArrayList<String> codes = new ArrayList<>();
        for(int i = 0; i<blocks.getLength(); i++){
            Element  children = (Element) blocks.item(i);
            if(children.getElementsByTagName("CODE") != null){
  • 1
    \$\begingroup\$ That looks a lot like something that XPath is well suited to. You might find that the subset of XPath support in xml.etree.ElementTree is good enough for this task. \$\endgroup\$ Aug 1 at 18:56
  • \$\begingroup\$ You mean I should use python? \$\endgroup\$
    – gbasic
    Aug 1 at 19:14
  • \$\begingroup\$ Welcome to Stack Review, you can use xpath with java too. If you want to send a message to an user use @name in your message, see how-do-comment-replies-work for further informations \$\endgroup\$ Aug 1 at 20:12
  • \$\begingroup\$ Oops, sorry - I had just reviewed a Python question, so had those docs to hand. I don't know what XPath libraries exist for Java, but it may be worth researching, as you may find that much of the work is done for you. \$\endgroup\$ Aug 1 at 20:37
  • 1
    \$\begingroup\$ XPath for java is in the package javax.xml.xpath. All contained in the standard library. \$\endgroup\$
    – mtj
    Aug 2 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.