我需要在XSD中声明的复杂类型的contentModel,我的XSD如下:
<element name="add">
<complexType>
<sequence>
<element name="no1" type="xsd:int" minOccurs="0"/>
<element name="no2" type="xsd:int" minOccurs="1" maxOccurs="5"/>
</sequence>
</complexType>
我为此使用以下代码:
//elem is ScheamType for the rootnode , in this case it is add
if (elem != null) {
System.out.println("\ncontent of "+elem +" is "+elem.getContentType());
if(elem.getContentType()==3||elem.getContentType()==4)
{
SchemaParticle particle=elem.getContentModel();
for( SchemaParticle p:particle.getParticleChildren())
{
System.out.println("\nchild:"+p.getName()+"\ttype:"+p.getType().getName().getLocalPart());
}
}
但是它为SchemaParticle对象提供了NullPointerException,该对象由getContentModel()返回
该代码适用于以下xsd:
<complexType name="Employee"> <sequence> <element name="empid" type="xsd:int"/> <element name="empname" nillable="true" type="xsd:string"/> </sequence> </complexType>
找到了解决方案:
//The elem is the SchemaType variable
SchemaParticle rootSchemaParticle = elem.getContentModel();
SchemaLocalElement rootSchemaLocalElement = (SchemaLocalElement) rootSchemaParticle;
//Get the SchemaType for the element.
SchemaType rootSchemaType = rootSchemaLocalElement.getType();
//Get the content Model of the root Element ie; the Children Structure for elem
SchemaParticle childrenSchemaparticle = rootSchemaType.getContentModel();
if (childrenSchemaparticle != null) {// Operation has non zero child element
if (childrenSchemaparticle.countOfParticleChild() > 0) {// multiple child elements
for (int i = 0; i < childrenSchemaparticle
.countOfParticleChild(); i++) {
paraName = childrenSchemaparticle.getParticleChild(i).getName().getLocalPart();
SchemaLocalElement childSchemaLocalElement = (SchemaLocalElement) childrenSchemaparticle.getParticleChild(i);
minOccur = childSchemaLocalElement.getMinOccurs().longValue();
maxOccur = childSchemaLocalElement.getMaxOccurs().longValue();
SchemaType childSchemaType = childSchemaLocalElement.getType();
dataType = childSchemaType.getName().getLocalPart();
System.out.println("parameter Name "+paraName + " Datatype "+dataType+" Minoccur "+minOccur+" MaxOccur "+maxOccur);
}
} else {// Single child
paraName = childrenSchemaparticle.getName().getLocalPart();
minOccur = childrenSchemaparticle.getMinOccurs().longValue();
maxOccur = childrenSchemaparticle.getMaxOccurs().longValue();
SchemaLocalElement childSchemaLocalElement = (SchemaLocalElement) childrenSchemaparticle;
SchemaType childSchemaType = childSchemaLocalElement.getType();
dataType = childSchemaType.getName().getLocalPart();
System.out.println("parameter Name "+paraName + " Datatype "+dataType+" Minoccur "+minOccur+" MaxOccur "+maxOccur);
}
}
处理单个孩子和多个孩子的差异是由于粒子类型的不同,因为单个孩子的ELEMENT和多个孩子的SEQUENCE。引用以获取详细信息:http : //xmlbeans.apache.org/docs/2.0.0/reference/org/apache/xmlbeans/SchemaParticle.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句