1

I have an XML string as response from server with some open tags, like: Example:

<Address1><Street>This caused error coz street is not closed</Address1>
<Address2>This displayed normal</Address2>

while i was parsing above xml string, i got, org.xml.sax.SAXParseException: The element type "Street" must be gathered.

Note: I Can't Change Server Files.

  • working solution but avoids inner tag like data which accidentally come between given tags, like in my case Street is data not tag in Address1 tag. – Kumar Gaurav Sharma Sep 16 '17 at 12:48

1 Answers1

1

First, I do not think you should work with invalid XML because it will lead to unpredictable results. The best for you is to update the server files to have valid XML content.

That being said, you can use Jsoup which is an HTML parser that can help to manage such invalid XML.

For your provided example:

String xml = "<Address1><Street>This caused error coz street is not closed</Address1><Address2>This displayed normal</Address2>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements elements = doc.getElementsByTag("Address1");
System.out.println(elements.first().text());
// it will print: "This caused error coz street is not closed"
Elements elements2 = doc.getElementsByTag("Address2");
System.out.println(elements2.first().text());
// it will print: "This displayed normal"

The Street element will simply be ignored.

Arnaud Develay
  • 3,920
  • 2
  • 15
  • 27