0
\$\begingroup\$

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:

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

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); doc.getDocumentElement().normalize(); 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){ codes.add(children.getElementsByTagName("CODE").item(0).getTextContent()); }else{ codes.add(""); } } } } 
\$\endgroup\$
7
  • 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\$CommentedAug 1, 2021 at 18:56
  • \$\begingroup\$You mean I should use python?\$\endgroup\$
    – gbasic
    CommentedAug 1, 2021 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\$CommentedAug 1, 2021 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\$CommentedAug 1, 2021 at 20:37
  • 1
    \$\begingroup\$XPath for java is in the package javax.xml.xpath. All contained in the standard library.\$\endgroup\$
    – mtj
    CommentedAug 2, 2021 at 10:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.