How to parse an xml string in Java

chand pb
chand pb used Ask the Experts™
on
Hello,
 How can parse the XML string in java so that i get an arraylist...

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Candidate>
      <EMPLID>1</EMPLID>
</Candidate>
<Candidate>
     <EMPLID>2</EMPLID>
</Candidate>
<Candidate>
     <EMPLID>3</EMPLID>
</Candidate>

Open in new window


I would like

arraylist[0] =
   <Candidate>
      <EMPLID>1</EMPLID>
</Candidate>

arraylist[1] =
  <Candidate>
      <EMPLID>2</EMPLID>
</Candidate>

arraylist[2]=
  <Candidate>
      <EMPLID>2</EMPLID>
</Candidate>

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016

Commented:
That's not actually xml - at least not well-formed xml. There is no root element
Senior Engineer
Commented:
As CEHJ said, there's no root element. This is an issue because one of the easier ways to "parse" this would be with XPath using a library like jxpath. If there was a root element surrounding all of your Candidate elements, then the simple XPath expression "*/Candidate" would accomplish your goal.

A simple solution given this limitation is the org.apache.commons StringUtils:
        String open = "<Candidate>";
        String close = "</Candidate>";

        String[] elems = StringUtils.substringsBetween(input, open, close);
        List<String> list = new ArrayList();
        for (String elem : elems) {
            list.add(open + elem + close);
        }

Open in new window

Top Expert 2016

Commented:
And i hope you haven't had to follow that suggestion, as you should have proper xml ;)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial