Unable to edit SVG using Batik in Java?

安稳与你 提交于 2019-12-04 06:02:20

问题


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

<text x="759" y="361" id="name" class="fil3 fnt3">STUDENT</text>

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();

回答1:


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.



来源:https://stackoverflow.com/questions/41800279/unable-to-edit-svg-using-batik-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!