簡體   English   中英

Java XML DocumentBuilderFactory寫空標簽 <Tag /> 從空值

[英]Java XML DocumentBuilderFactory write empty tags <Tag /> from null values

嘿,所以我想知道如何用DocumentBuilderFactory (基於此資源 ,庫javax.xml.parsers.*; )編寫一個空標簽,例如<Category /> ,就目前而言,如果條件為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>

而且我注意到,如果我添加了一個null的textnode,則是converter.transform transformer.transform(source, result); 將返回一堆NullException錯誤。 有沒有一種方法可以配置轉換器以知道TextNode被故意留空了? 然后依次創建<Category /><Category></Category>

//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時才添加文本節點子元素。 如果為null,則將創建一個空的category元素,該元素將作為<category />序列化為XML。

如果你希望能夠在一間XML區分null的值excel.getCategory()和一個空字符串值,然后為通常的XML模式成語是使元素“的nillable”

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM