Saving and modifying the XML document
What if you want to write the document back to the file system?
That's easy: add this line to your program:
webappDoc.save(new File("c:/webapp.xml"));
If you look in the output file you'll be impressed to see that
it's an exact copy of your original document. Even the comments
and formatting are preserved!
To add elements to your xml document it is also very easy. If we
want to add another servlet-mapping we could code it like this:
ServletMapping newSM = webapp.addNewServletMapping();
newSM.setServletName("action2");
newSM.setUrlPattern("done.*");
You may control where the new servlet-mapping element is
inserted. Use an index to show the position, zero means "at
the beginning":
// Insert new element before the others:
ServletMapping newSM = webapp.insertNewServletMapping(0);
newSM.setServletName("action2");
newSM.setUrlPattern("done.*");
If you want to update some of the data in the document you use
the setter-methods. To change the name of the welcome-file we
use this code:
WelcomeFileList fileList = webapp.getWelcomeFileList();
fileList.setWelcomeFileArray(new String[]{"welcome.htm"});
To keep the XML document pretty-printed you have several options
to apply to the save method, e.g.:
XmlOptions opt = new XmlOptions();
opt.setSavePrettyPrint();
opt.setSavePrettyPrintIndent(3);
webappDoc.save(new File("c:/webapp.xml"), opt);
I'll encourage you to use the JavaDoc to see the many methods
that are available. If you use a tool like Eclipse the code-complete
feature may also help you to inspect the methods that are at
hand.
Package names
In the FirstTry program you may have noticed the
names of the package in the generated jar-file:
noNamespace. XMLBeans takes the package name from
the namespace definition in the schema file, so let's make a new
schema element like this:
<xsd:schema
targetNamespace="http://playground.hansen.dk"
elementFormDefault="qualified"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
In the XML instance file we must add the same namespace:
<web-app xmlns="http://playground.hansen.dk">
When we generate the jar file this time the package name will be
dk.hansen.playground, so the only thing that needs
to be changed in the FirstTry program is the
import statements.
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.