Writing XML by hand is a very painful task. Writing schema by hand is even more painful, that is, using xmlspy, or something that cannot be written, such as complicated data restrictions.
Xmlbeans is a Java Bean generation tool donated by BEA to Apache based on Schema. The above schema is compiled:
Scomp-Src SRC test. XSD
Generate the following class: (Note that the package is the targetnamespace of XSD and can be adjusted through the configuration file)
The Gender Enumeration type is automatically generated to generate nested enumeration classes. Is it very convenient?
Public Interface Gender extends org. Apache. xmlbeans. xmlstring
{
StaticFinal Enum male=Enum. forstring ("Male");
StaticFinal Enum female=Enum. forstring ("Female");
}
Test:
Arenumber Area = Arenumber. Factory. newinstance ();
Area. setstringvalue ( " 0467 " );
System. Out . Println (area );
System. Out . Println ( " Verification Result: " + Area. Validate ());
Gender gender = Gender. Factory. newinstance ();
Gender. setstringvalue (gender. Female. tostring ());
System. Out . Println (gender );
System. Out . Println ( " Verification Result: " + Gender. Validate ());
Chinesename CN = Chinesename. Factory. newinstance ();
CN. setstringvalue ( " Li " );
System. Out . Println (CN );
System. Out . Println ( " Verification Result: " + CN. Validate ());
Running result:
<XML-fragment>
0467
</XML-fragment>
Verification Result: True
<XML-fragment>
Female
</XML-fragment>
Verification Result: True
<XML-fragment>
Li
</XML-fragment>
Verification Result: false
Note:
The result of chinesename verification is false because the length does not match.
Because schematype only describes data, <XML-fragment> is only an anonymous container.
In addition to the newinstance () and validate () methods above, there are some other practical methods:
Gender. Factory. newvalue (object ); // Generate new instance
Gender. Factory. parse (File );
Gender. Factory. parse (Reader );
Gender. Factory. parse (inputstream );
Gender. Factory. parse (node );
Gender. Factory. parse (URL );
Gender. Factory. parse (string );
CN. newdomnode (); // Generate dom
CN. newinputstream (); // Generate inputstream
CN. newreader (); // Generate Reader
CN. xmltext (); // Generate XML text
CN. schematype (); // Get the compiled schema. Use it later
CN. Save (File );
CN. Save (writer );
CN. Save (outputstream );
CN. selectpath ( " Some/path [here = 'where'] " ); // Xpath