我有一个没有任何子节点的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做到这一点?
答案 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);