nilsi nilsi - 24 days ago 6
Java Question

XML formatted Java string manipulation

I'm developing a plugin that has

node(computer)
objects with attributes like:

String name
String description
String labels
Launcher computerLauncher
...


I can convert the
node(computer)
object to an XML-formated String like:

String xml = jenkins.instance.toXML(node);


Which gives me a string:

<name>Computer1</name>
<description>This is a description</description>
<labels>label1 label2</labels>
<launcher>windows.object.launcher.12da1</launcher>


Then I can go the other way back:

Node node = jenkins.instance.fromXML(xml);


I have no methods for changing attributes in a Node so I want to convert it to XML, change som attributes and then make it a Node again.

I see two options


  1. Manipulate the XML with some String methods to replace everything in between the <> tags.

  2. Try to cast the XML string to something like a real Object and manipulate it that way.



Not sure what would be the best approach.

Answer

Why invent something new when there already is support for all that using Java's DOM (Document Object Model) API?

Use a DocumentBuilderFactory to get a DocumentBuilder and create a Document instance. With this you can create the 'Node' objects (please note that the example you posted is actually not valid XML, it's missing a root node) in your toXML method, serializing the Document to a String could be done by using a Transformer.

With the DOM API you can also modify the attributes of your existing elements.

Parsing the Document instance from an XML string is realized again with the help of the DocumentBuilder, using DocumentBuilder#parse.

If your DOM operations are not too complex this should be a nice, quick way to accomplish your goal.