使用XMLBeans为空元素生成结束标记

时间:2011-07-17 18:23:37

标签: xsd marshalling unmarshalling xmlbeans

我有以下xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="employee" type="employeeType"/>
  <xs:complexType name="employeeType">
    <xs:sequence>
      <xs:element type="xs:string" name="name"/>
      <xs:element type="xs:int"  name="age"/> 
      <xs:element type="xs:string" name="address"/>          
    </xs:sequence>
  </xs:complexType>
</xs:schema>

如果我为Name设置值 ,即

 EmployeeDocument request=EmployeeDocument.Factory.newInstance();
 EmployeeType emp=EmployeeType.Factory.newInstance();
 emp.setName("Name");
 request.setEmployee(emp);

然后XMLBeans生成以下xml:

<employee>
    <name>Name</name>
</employee>

但我需要生成以下类型的xml,意味着为所有未在程序中设置值的元素关闭标记</>

<employee>
    <name>Name</name>
    <age/>
    <address/>
</employee>

好吧,如果我设置一个空字符串,<address/>

,XMLBeans会生成emp.setAddress("");

我们是否有任何方法可以使用XMLBeans满足此类要求,而无需设置空字符串。

而且我们无法为元素年龄设置空字符串,类型为int。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

XMLSchema执行此操作的方法是将nillable="true"添加到您的年龄和地址元素中。使用XMLBeans重新编译xsd时,将使用.setNilAge().setNilAddress()方法。生成的xml将如下所示:

<employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <name>Name</name>
  <age xsi:nil="true"/>
  <address xsi:nil="true"/>
</employee>

顺便说一句,如果可能的话,最好使用.addNewEmployee()而不是.setEmployee()来构建文档。这样可以避免将员工实例复制到更昂贵的文档中。

相关问题