-1

I have an XML element without any children. Its node value is:

<property key="TYPES_TO_EXCLUDE_IN_COLLECTOR_PROCESSING"/>

And I am trying to create a first child of this element and want to set a value to it, e.g. like this:

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

How can I do this in Java?

SAGAR MANE
  • 685
  • 2
  • 8
  • 23
  • 2
    Can you give an example of what the resulting xml would look like? Also, do you have example code of what you've tried so far? – Garett Feb 26 '17 at 05:49
  • I improved the formatting of the question and added an example of the desired outcome. – zx485 Feb 27 '17 at 20:39

1 Answers1

0

Here's one way you could do it.

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);
Garett
  • 16,632
  • 5
  • 55
  • 63