如何使用Java在XML中创建(第一个)子元素?

时间:2017-02-24 13:04:54

标签: java xml xml-parsing xmlreader

我有一个没有任何子节点的XML元素。其节点值为:

[DEBUG|imap.py:81]2017-02-24 21:43:57,921 > STORE command error: BAD [b'Error in IMAP command STORE: Invalid messageset'] 

我正在尝试创建此元素的第一个孩子,并希望为其设置一个值,例如像这样:

<property key="TYPES_TO_EXCLUDE_IN_COLLECTOR_PROCESSING"/>

我怎样才能用Java做到这一点?

1 个答案:

答案 0 :(得分: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);