0

嘿,所以我想知道如何<Category />使用DocumentBuilderFactory (基于此资源,库javax.xml.parsers.*;)编写一个空标签,因为目前我必须应用一个 if 条件if object.getCategory() != null然后创建Category Tag否则忽略它。

//add the Category
if(excel.getCategory() != null){
    Element Category = doc.createElement("category");
    Category.appendChild(doc.createTextNode(excel.getCategory()));
    Rows.appendChild(Category);
}

和架构

<xs:complexType name="data">
    <xs:all>
    <xs:element name="Category" type="xs:string" minOccurs="1" />
    <!-- other columns.. -->
    </xs:all>
</xs:complexType>

而且我注意到如果我添加一个为空的文本节点,transformer.transform(source, result);它将返回一堆NullException错误。有没有办法配置转换器以知道 TextNode 是故意留空的?进而创建<Category />or <Category></Category>

4

1 回答 1

1
//add the Category
Element Category = doc.createElement("category");
Rows.appendChild(Category);
if(excel.getCategory() != null){
    Category.appendChild(doc.createTextNode(excel.getCategory()));
}

在这里,我无条件地添加category元素Rows,但仅在getCategory()非空时添加文本节点子节点。如果它为 null,那么这将创建一个空category元素,该元素将序列化为 XML 为<category />.

如果您希望能够在 XML 中区null分值excel.getCategory()和空字符串值,那么通常的 XML 模式习惯用法是使元素“可空”

<xs:complexType name="data">
    <xs:all>
    <xs:element name="Category" type="xs:string" nillable="true" />
    <!-- other columns.. -->
    </xs:all>
</xs:complexType>

并用xsi:nil

//add the Category
Element Category = doc.createElement("category");
Rows.appendChild(Category);
if(excel.getCategory() != null){
    Category.appendChild(doc.createTextNode(excel.getCategory()));
} else {
    Category.setAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
                            "xsi:nil", "true");
}

这将产生

<category />

何时excel.getCategory().equals("")

<category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />

什么时候excel.getCategory() == null

于 2013-01-27T22:29:05.533 回答