Unable to edit SVG using Batik in Java?
Asked Answered
A

1

0

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();
Asclepiadaceous answered 23/1, 2017 at 6:17 Comment(0)
S
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.

Slier answered 26/1, 2017 at 3:58 Comment(3)
FileOutputWriter ?Asclepiadaceous
Sorry, FileWriter. (It's been a while since I've done any Java.)Slier
Your Update #2 looks about right to me. Please ask on the batik-users mailing list if you still have trouble.Slier

© 2022 - 2024 — McMap. All rights reserved.