I have never had need to add XML elements in files before other than the initial creation of them with a printwriter object to write the XML to disk. Now I have a project that requires that I parse existing XML and find certain elements and to add child elements and values to those children. I can parse the document and add the child element through:
Once I have this value in my DOM, is there any open source API or package in Java that you are aware of that will take the modified DOM and just rewrite the xml file on disk with it? Or, should I just create my own methods to do the same thing (overwriting the file with some precautions taken)?
You already have revised the xml inside the DOM object, and you want just to save the xml under it?
If so, try this:
The DOM implementation you used to revise the xml, can do it for you too.
private static final String MY_FILE = "revised.xml";
....do the xml revision here
PrintWriter writer = new PrintWriter(new FileWriter(MY_FILE)); writer.println(((DocumentImpl)doc).saveXML(null)); writer.close();
The 'doc' variable is your variable that 'is a' DocumentImpl.
Joined: Dec 20, 2005
That will do take care of it I am sure. Thanks for the help and guidance.
Joined: Feb 26, 2005
I think my code is for xerces implementation of dom. Other implementations might have their own 'method' too.
What are you using? xerces? jaxp?
Joined: Dec 20, 2005
After I read your post, I did a search on "documentimpl" and xerces first popped up so I figured that was what you were referencing. I have been just using org.xml.sax and org.w3c.dom packages of the Java API. I was just about to read about xerces (which I had heard of but never had need to study before). From your suggestion, it sounds like that package will do what I need.
DOM version 3 introduced a standard way to load and save DOM objects. If you are running Java 5, you have DOM 3 built in, and should use that instead of parser-specific classes (which you would need to change if you ever want to use a different parser). Look for the org.w3c.dom.ls package in your JDK javadocs.
LSSerializer and DOMImplementaionLS looks like it may work... I figured that there was something in the API that would take care of this. Thanks very much. That saves me having to learn another API right now!