0

I have the following element declaration:

<xs:element name="period" type="xs:unsignedInt" default="20"/>

I use it as follows:

<period/>

It is somehow expected that:

    XMLEvent event = eventReader.nextEvent();

    if (event.isStartElement()) {
      StartElement startElement = event.asStartElement();

      switch (startElement.getName().getLocalPart()) {
        case "period":
          int period = Integer.parseInt(eventReader.nextEvent().asCharacters().getData())
        // do something with period
        default:
      }
    }

throws an

Exception in thread "main" java.lang.ClassCastException 
com.sun.xml.internal.stream.events.EndElementEvent cannot be cast to 
javax.xml.stream.events.Characters

How can I retrieve the default value of an element using StAX? Should I parse the corresponding XML Schema, too? My gut says that there should be other, more convenient solutions.

Nesze
  • 306
  • 3
  • 8

1 Answers1

0

If you tell the parser to validate the document, and tell it which schema or DTD to validate against, default values defined therein will be filled in automagically during parsing.

If you don't validate, they probably won't be. (Theoretically a mode may be offered where defaults are applied but validation constraints aren't, but that's not guaranteed to be available; check your parser's documentation.)

keshlam
  • 7,931
  • 2
  • 19
  • 33
  • I managed to do this with DOM. With StAX, according to this thread [link](http://stackoverflow.com/questions/5793087/stax-xml-validation) implementing my own StreamReaderDelegate is the only way to do it. – Nesze Jun 24 '14 at 20:25