devxlogo

Assembling XML with String Operations

Assembling XML with String Operations

String name = …String attribute = …String xml = ""+""+ name +""+";

Many beginners are tempted to create an XML file like the one listed above using String operations because it is easier, but this approach fails to escape reserved characters. If one of the variable name or attribute contain any of the reserved characters <,>,&, ” or ‘ the result would be invalid.

The solution would be that the XML should be assembled in a DOM, using the JDom library, like this:

Element root = new Element("root");Root.setAttribute("attribute", attribute);Root.setText(name);Document doc = new Document();doc.setRootElement(root);XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());String xml = out.outputString(root);
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist