How to parse invalid XML in Java

0 votes

Currently, I'm working on a feature that involves parsing XML that we receive from another product. I decided to run some tests against some actual customer data, and it looks like the other product is allowing input from users that should be considered invalid. Anyways, I still have to try and figure out a way to parse it. We're using javax.xml.parsers.DocumentBuilder and I'm getting an error on input that looks like the following.


As you can tell, the description has what appears to be an invalid tag inside of it (<THIS-IS-PART-OF-DESCRIPTION>). Now, this description tag is known to be a leaf tag and shouldn't have any nested tags inside of it. Regardless, this is still an issue and yields an exception on DocumentBuilder.parse(...)

I know this is invalid XML, but it's predictably invalid. Any ideas on a way to parse such input?

Mar 7, 2019 in Java by Sushmita
• 6,910 points

1 answer to this question.

0 votes

That "XML" is worse than invalid – it's not well-formed.

An informal assessment of the predictability of the transgressions does not help. That textual data is not XML. No conformant XML tools or libraries can help you process it.

Options, most desirable first:

  1. Have the provider fix the problem on their end. Demand well-formed XML. (Technically the phrase well-formed XML is redundant but may be useful for emphasis.)
  2. Use a tolerant markup parser to cleanup the problem ahead of parsing as XML:

    • Standalone: xmlstarlet has robust recovering and repair capabilities credit: RomanPerekhrest

      xmlstarlet fo -o -R -H -D bad.xml 2>/dev/null
    • Standalone and C: HTML Tidy works with XML too.

    • Python: Beautiful Soup is Python-based.
    • Java: JSoup focuses on HTML. FilterInputStream can be used for preprocessing cleanup.
    • .NET:

      • XmlReaderSettings.CheckCharacters can be disabled to get past illegal XML character problems.

      • @jdweng reports that XmlReader.ReadToFollowing() can sometimes be used to work-around XML syntactical issues, but note rule-breaking warning in #3 below.

      • Microsoft.Language.Xml.XMLParser is said to be “error-tolerant”.
    • PHP: See DOMDocument::$recover and libxml_use_internal_errors(true).
    • Ruby: Nokogiri supports “Gentle Well-Formedness”.
    • R: See htmlTreeParse() for fault-tolerant markup parsing in R.
  3. Process the data as text manually using a text editor or programmatically using character/string functions. Doing this programmatically can range from tricky to impossible as what appears to be predictable often is not -- rule breaking is rarely bound by rules.

    • For invalid character errors, use regex to remove/replace invalid characters:
      • PHP: preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $s);
      • Ruby:"^\u{0009}\u{000a}\u{000d}\u{0020}-\u{D7FF}\u{E000‌​}-\u{FFFD}", ' ')
      • JavaScript: inputStr.replace(/[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm, '')
    • For ampersands, use regex to replace matches with &amp;: credit: blhsindemo


    Note that the above regular expressions won't take comments or CDATA sections into account.

answered Mar 7, 2019 by developer_1
• 3,320 points

Related Questions In Java

0 votes
3 answers

How to parse JSON in Java

import org.json.*; JSONObject obj = new JSONObject(" .... ...READ MORE

answered Aug 20, 2018 in Java by Daisy
• 8,120 points
+1 vote
1 answer

if i given invalid data how to get alert in selenium using java

Hello, Here is some of the method you ...READ MORE

answered Jul 20, 2020 in Java by Niroj
• 82,880 points
0 votes
0 answers

How to set XML Attribute inside XML Element in Java Pojo Class - JAVX

How can I get this Output Response? <Response> ...READ MORE

Apr 19, 2022 in Java by Rahul
• 3,380 points
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 7, 2018 by Omkar 79,553 views
0 votes
1 answer

How to read an XML file using XPath in Java?

Import the packages required to work with ...READ MORE

answered Jun 14, 2018 in Java by Akrati
• 3,190 points
0 votes
1 answer

How to pretty print XML from Java?

Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{}indent-amount", "2"); //initialize StreamResult ...READ MORE

answered Jul 4, 2018 in Java by Akrati
• 3,190 points
0 votes
1 answer

org.xml.sax.SAXParseException: How to handle this exception?

This is often caused by a white ...READ MORE

answered Jul 9, 2018 in Java by sharth
• 3,370 points
0 votes
1 answer

Hosting spring boot app

There are a couple of things wrong ...READ MORE

answered Sep 11, 2018 in AWS by Priyaj
• 58,090 points
0 votes
3 answers

How can I add new elements to an Array in Java

String[] source = new String[] { "a", ...READ MORE

answered Sep 19, 2018 in Java by Sushmita
• 6,910 points
0 votes
1 answer

How to refresh data in ViewPager Fragment ?

Using the ViewPager.OnPageChangeListener is the correct way to go, ...READ MORE

answered Mar 7, 2019 in Java by developer_1
• 3,320 points
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP