John Baker
John Baker

Reputation: 109

SimpleXML - how to ignore duplicate tags in bad XML?

I am using java SimpleXML to parse XML from a number of applications.

Many applications create quirky XML implementations of this supposed 'standard', such as putting in an 'enabled' tag more than once.

In this situation, I just want to ignore the second one as it is a mistake and has same value as first anyway, but SimpleXML throws an exception "Element 'enabled' is already used"

How do I prevent this?

This is the field that is complained about.

@Element(required = false)
protected boolean enabled = true;

The XML is huge so don't want to post it. Is there a way to get SimpleXML to report the line number that the caused the error?

Upvotes: 0

Views: 615

Answers (1)

Marcus Bleil
Marcus Bleil

Reputation: 149

try to following annotations:

   class RepeatElements {
      @ElementListUnion({
         @ElementList(entry = "enable", 
           type = Boolean.class, inline = true)
        })
      private ArrayList<Boolean> enables = new ArrayList<>();

      public boolean isEnabled() {
        // TODO check size
        return enables.get(0).booleanValue();
      }
    }

ouput for class RepeatElements with some "enables"

    <repeatElements>
        <enable>true</enable>
        <enable>true</enable>
        <enable>true</enable>
    </repeatElements>

Upvotes: 1

Related Questions