你可以使用众多Java XML库之一来提取名称。以下是使用XPath从
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;
}
注意:可能是打字错误,但您的XML格式不正确 - 属性值必须加上引号。否则,XML解析将失败。
![some boxes](https://istack.dev59.com/OE8F1.webp)
你可以使用
AWT API画出你想要的任何东西:
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;
}
}
这段代码只是在名称周围绘制一些框。我确定我的偏移量都错了,但你可能已经明白了。
有一个
imageio API可以保存几种流行的数据格式:
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);
}