About working with XML files using common Digester
Source: Internet
Author: User
XML now many software use XML as a configuration file, but still very cumbersome to deal with, in the Jakarta Project project, there is a common Digester package can help us deal with XML type of configuration file.
In addition to reading XML configuration files, this software is also ideal for converting XML to JavaBean.
Suppose the XML file is as follows:
<foo name= "The Parent" >
<bar id= "123" title= "the" "The" "The" "the"
<bar id= "456" title= "the Second Child"/>
</foo>
The corresponding JavaBean class is defined as follows:
public class Bar {
private int id;
Private String title;
public int getId () {
return ID;
}
public void setId (int id) {
This.id = ID;
}
Public String GetTitle () {
return title;
}
public void Settitle (String title) {
This.title = title;
}
}
public class Foo {
private String name;
Private vector bars = new vector ();
public void Addbar (bar bar) {
Bars.add (bar);
}
Public Bar findbar (int id) {
Iterator iterator = Bars.iterator ();
if (Iterator.hasnext ()) {
Bar bar = (bar) iterator.next ();
if (bar.getid () = = ID) {
return bar;
}
}
return null;
}
Public iterator Getbars () {
return Bars.iterator ();
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}
In later processing, you can convert an XML-described object to a JavaBean object simply by simply processing it.
Digester digester = new Digester ();
Digester.setvalidating (FALSE);
Digester.addobjectcreate (foo, mypackage.) Foo);
Digester.addsetproperties (foo);
Digester.addobjectcreate (Foo/bar, MyPackage. Bar);
Digester.addsetproperties (Foo/bar);
Digester.addsetnext (Foo/bar, Addbar, MyPackage. Bar);
try {
Foo foo = (foo) digester.parse (d:/java/eclipse/workspace/digester/src/mypackage/utils/bar.xml);
System.out.println (foo);
catch (IOException e) {
E.printstacktrace ();
catch (Saxexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
On the Sentom website, there is a detailed description of the document.
Phase Seventh-jakarta Commons Digester
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service