java batik,无法在Java中使用Batik编辑SVG?

这篇博客讲述了如何通过Java解析SVG文件,并修改其中的元素内容,如姓名和ID。作者成功使用了Batik库的SAXSVGDocumentFactory来读取SVG,但发现更改并未体现在实际文件中。解决方案是通过XmlWriter将修改后的DOM写入新的SVG文件,确保更改被保存下来。
摘要由CSDN通过智能技术生成

I have a student card SVG that has name, id and other field that I want to edit through Java, as the user inputs them using GUI.

I have successfully parsed the SVG using Batik but I can't see the changes that I made in SVG file when I open it.

String parser = XMLResourceDescriptor.getXMLParserClassName();

SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);

String uri = "card.svg";

try {

Document doc = f.createDocument(uri);

NodeList nodeList = doc.getChildNodes();

Element svg = doc.getElementById("name");

svg.setTextContent("Your Name");

System.out.println(svg.getTextContent());

} catch (IOException e) {

e.printStackTrace();

}

When I print out one the of SVG element's value using

System.out.println(svg.getTextContent());

It's changed but when I open the SVG in notepad it's the same.

SVG

STUDENT

UPDATE FOR OTHERS: Solved with

File file = new File("new.svg");

FileWriter fWriter = new FileWriter(file);

XmlWriter.writeXml(svg, fWriter, false);

// Most crucial part, It wasn't working just because of flush

fWriter.close();

解决方案

It looks like you aren't using any particular SVG features here, just some generic XML parsing. The result of parsing the document with createDocument is a DOM in memory, but that doesn't automatically write out your changes to a file. You'll have to do that explicitly. Using the org.apache.batik.svggen.XmlWriter class is one of serializing. You'll need to open a file for writing, and pass the FileWriter to it, along with the Document node.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值