Create a graphic image (png, jpg ..) from an XML file with Java

I have an XML file and I want to create a graph with some objects, and then save this graph in an image, jpg or png.

So is there a library in Java like this? Or are there some tricks when parsing XML files and ... ???

Here is an example XML file:

<?xml version="1.0"?> <process> <pn="1">Tove</p> <pn="2">Jani</p> <pn="2">Bill</p> <pn="4">John</p> </process> 

And the result will be like this:

enter image description here

+6
java xml graph image
source share
3 answers

You can extract names using one of the many Java XML libraries. Here is an example of using XPath from the Java DOM :

 private static List<String> findNames(Document doc) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate("/process/p", doc, XPathConstants.NODESET); List<String> names = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { names.add(nodes.item(i).getTextContent()); } return names; } 

Note: this may be a typo, but your XML is not very well formed - attribute values ​​must be specified. XML parsing fails otherwise.

some boxes

You can use the AWT API to draw everything you need:

 private static final int BORDER = 1; private static final int PADDING = 2; private static final int SPACER = 5; private static void draw(Graphics2D g, List<String> names) { FontMetrics metrics = g.getFontMetrics(); Rectangle box = new Rectangle(1, 1, 0, 0); box.height = metrics.getHeight() + (PADDING * 2); g.setColor(Color.WHITE); for (String name : names) { box.width = metrics.stringWidth(name) + (PADDING * 2); g.drawString(name, box.x + BORDER + PADDING, PADDING + BORDER + metrics.getHeight()); g.drawRect(box.x, box.y, box.width, box.height); box.x += box.width + (BORDER * 2) + SPACER; } } 

This code simply draws names with some fields around them. I'm sure my biases are everywhere, but you probably understood.

There is an imageio API that can save in several popular data formats:

 private static void save(List<String> names, File file) throws IOException { BufferedImage image = new BufferedImage(600, 50, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); try { draw(g, names); } finally { g.dispose(); } ImageIO.write(image, "png", file); } 
+7
source share

I would parse the XML and derive a Graphviz DOT representation as follows:

 digraph { Tove -> Jani Jani -> Bill Bill -> John } 

Then I would name the Graphviz dot executable from Java using ProcessRunner:

 dot -Tpng -o file.png file.dot 

See http://graphviz.org for more details.

+6
source share

Thanks everyone!

I found a class in java that is corporate with GraphViz , so that an extra image at the end after parsing the XML file and outputting the GraphViz view, follow this link . Good with two McDowell methods. I can easily parse XML files.

Best wishes

0
source share

All Articles