Search code examples
javaxmlparsingxmlbeans

Getter on xmlbeans generated class returning null and it shouldn't


Using this simplified XSD (simplified, but still verbose as all XSDs tend to be):

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="[redacted]">
 <xsd:element name="Statement" type="BILLINGSTATEMENTTYPEType"/>

 <xsd:complexType name="BILLINGSTATEMENTTYPEType">
  <xsd:sequence>
   <xsd:element name="AccountSection" type="ACCOUNTSECTIONTYPEType"/>
   <xsd:element name="DataSection" type="DATASECTIONTYPEType"/>
   <xsd:element name="Summary" type="SUMMARYTYPEType"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="ACCOUNTSECTIONTYPEType">
  <xsd:sequence>
    <xsd:element name="Foo" type="xsd:string" maxOccurs="unbounded" minOccurs="0"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="DATASECTIONTYPEType">
  <xsd:sequence>
   <xsd:element name="Bar" type="xsd:string" maxOccurs="unbounded" minOccurs="0"/>
  </xsd:sequence>
 </xsd:complexType>

 <xsd:complexType name="SUMMARYTYPEType">
  <xsd:sequence>
   <xsd:element name="Baz" type="xsd:string" maxOccurs="unbounded" minOccurs="0"/>
  </xsd:sequence>
 </xsd:complexType>

</xsd:schema>

I generated a JAR file (using the <xmlbean> Ant task from xmlbeans), and everything appears to look great, I get all the right types and whatnot. But when I have it parse this simplified document:

<Statement>
    <AccountSection>
        <Foo>bar</Foo>
    </AccountSection>
    <DataSection>
    </DataSection>
    <Summary>
    </Summary>
</Statement>

Using this code:

public class XmlTest {
    public static void main(String[] args) throws Exception {
        File xmlFile = new File("./data/test.xml");
        FileInputStream xmlStream = new FileInputStream(xmlFile);

        BILLINGSTATEMENTTYPEType statement = BILLINGSTATEMENTTYPEType.Factory.parse(xmlStream);

        ACCOUNTSECTIONTYPEType acctSection = statement.getAccountSection();

        System.out.println(statement.xmlText());
        System.out.println("acctSection is null:" + (acctSection == null));
    }
}

The acctSection (and any of the child sections I've tried) are always null, even though it is fully parsing the document.

Output:

<Statement>
    <AccountSection>
        <Foo>bar</Foo>
    </AccountSection>
    <DataSection>
    </DataSection>
    <Summary>
    </Summary>
</Statement>
acctSection is null:true

Why is it null? Why are they all null? Did I improperly define something somewhere in my XSD? I've used xmlbeans before successfully and never had this issue, which is why I'm sure I'm missing something but I've been unable to find it.


Solution

  • I'm not an export in xmlbeans myself, but I noticed that you used the Factory of the complex type to parse the xml. Can you try to use StatementDocument.Factory instead?