2017-02-24 60 views
-1

我有一個沒有任何孩子的XML元素。它的節點值是:如何使用Java在XML中創建(第一個)子元素?

<property key="TYPES_TO_EXCLUDE_IN_COLLECTOR_PROCESSING"/> 

,我試圖創建一個第一個孩子該元素的並希望將值設置爲它,例如像這樣:

<property key="TYPES_TO_EXCLUDE_IN_COLLECTOR_PROCESSING"> 
    Some value 
</property> 

我怎樣才能做到這一點在Java中?

+2

你能舉一個例子,說明結果的xml是什麼樣的?另外,你是否有迄今爲止嘗試過的示例代碼? – Garett

+0

我改進了問題的格式並添加了期望結果的示例。 – zx485

回答

0

以下是你可以做到的一種方法。

String xml = "<property key=\"TYPES_TO_EXCLUDE_IN_COLLECTOR_PROCESSING\"/>";    

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = domFactory.newDocumentBuilder(); 

InputSource inputSource = new InputSource(new StringReader(xml)); 
Document doc = builder.parse(inputSource);   

Text value = doc.createTextNode("Some value"); 
Node property = doc.getFirstChild(); 
property.appendChild(value); 

// Could also do the following if you have more than one property element 
// You can then refer to any property based on it's position (index) 
//NodeList nodes = doc.getElementsByTagName("property"); 
//nodes.item(0).appendChild(value); 
+0

我更新了問題示例..請檢查 –

+0

我已更新示例代碼 – Garett

相關問題