![](/img/trans.png)
[英]Java XML parsing with DocumentBuilderFactory - null nodes?
[英]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.