xml version="1.0" encoding="UTF-8"?>
admin
18
8000
zhangsan
19
6000
具体步骤
1、确定输入流
2、获取docment对象
3、获取根节点
4、使用迭代器迭代emps节点下的节点
5、获取属性节点attribute(“id”),获取节点对象的属性值
6、迭代emp节点下的子节点
<emps>
<emp id="0001">
<name>admin1name>
<age>20age>
<salary>7000salary>
emp>
<emp id="0002">
<name>admin2name>
<age>21age>
<salary>7001salary>
emp>
emps>
public class ReadXML {
public static void main(String[] args) throws Exception {
List<Emp> empList = new ArrayList<Emp>();
// 1、确定输入流
SAXReader reader = new SAXReader();
// 2、获取docment对象
Document document = reader.read(new File("config/emp.xml"));
// 3、获取根节点
Element rootElement = document.getRootElement();
System.out.println(rootElement.getName());
// 4、使用迭代器迭代emps节点下的节点
Iterator<Element> it = rootElement.elementIterator();
while (it.hasNext()) {
Emp emp = new Emp();
Element element = it.next();
System.out.println(element.getName());//输出emp
// 5、获取属性节点attribute("id"),获取节点对象的属性值getValue()
// String id = element.attribute("id").getValue();
// System.out.println(id);
System.out.println(element.attributeValue("id"));
emp.setId(element.attributeValue("id"));
// 6、迭代emp节点下的子节点
Iterator<Element> it2 = element.elementIterator();//emp下的标签
while (it2.hasNext()) {
Element element2 = it2.next();
System.out.println("\t" + element2.getText());
if (element2.getName().equals("name")) {
emp.setName(element2.getText());
}
if (element2.getName().equals("age")) {
emp.setAge(Integer.parseInt(element2.getText()));
}
if (element2.getName().equals("salary")) {
emp.setSalary(Integer.parseInt(element2.getText()));
}
}
empList.add(emp);
}
System.out.println(empList);
}
}
具体步骤
1、准备数据
2、创建Document对象
3、document对象中添加element
4、输出流把Document写到数据文件
public class WriterXML {
public static void main(String[] args) throws Exception {
//准备数据
List<Emp> list = new ArrayList<>();
list.add(new Emp("0001","admin1",20,7000));
list.add(new Emp("0002","admin2",21,7001));
//1、Document对象
Document document = DocumentHelper.createDocument();
//2、document对象中添加element
//添加根节点
Element rootelement = document.addElement("emps");
//添加emp节点,根据list集合元素的个数
for(Emp emp :list) {
Element empelement = rootelement.addElement("emp");
empelement.addAttribute("id",emp.getId());
Element nameelement = empelement.addElement("name");
nameelement.addText(emp.getName());
Element ageelement = empelement.addElement("age");
ageelement.addText(emp.getAge()+"");
Element salary = empelement.addElement("salary");
salary.addText(emp.getSalary()+"");
}
//3、输出流把Document写到数据文件
XMLWriter writer =
new XMLWriter(new FileOutputStream("config/emp2.xml"),OutputFormat.createPrettyPrint());
writer.write(document);
writer.close();
}
}
解析含bean.xml文件
<beans>
bena>
beans>
public class Emp implements Serializable{
/**
* 序列化
*/
private static final long serialVersionUID = 1L;
private String id;
private String name;
private int age;
private int salary;
public Emp() {
}
public Emp(String id, String name, int age, int salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + salary;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Emp other = (Emp) obj;
if (age != other.age)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (salary != other.salary)
return false;
return true;
}
}
public class EmpDAO {
public void insert() {
System.out.println("数据添加!!!");
}
}
public class EmpService {
private EmpDAO empdao;
public void addEmp() {
// TODO Auto-generated method stub
empdao.insert();
}
}
public class BeanFactory {
private static Map<String, Object> map =new HashMap<>();
static {
try {
init();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void init() throws Exception {
//1、解析xml文件
SAXReader reader = new SAXReader();
Document document = reader.read("config/Bean.xml");
Element rootelement = document.getRootElement();//beans
Iterator<Element> it = rootelement.elementIterator();
while( it.hasNext()) {
Element beanElement =it.next();
String id = beanElement.attributeValue("id");
String className = beanElement.attributeValue("class");
System.out.println(id+","+className);
//2、通过反射创建两个对象
Class class1 = Class.forName(className);
Object obj = class1.newInstance();
//3、设置到map集合
map.put(id,obj);
//4、给service类到属性赋值
Iterator<Element> it2 = beanElement.elementIterator();
while(it2.hasNext()) {
Element propertyelement = it2.next();
String name = propertyelement.attributeValue("name");
System.out.println(name);
String ref = propertyelement.attributeValue("ref");
Field field = class1.getDeclaredField(name);
field.setAccessible(true);
field.set(obj,map.get(ref));
}
}
}
public static Object getBean(String key) {
return map.get(key);
}
}
public class Test {
public static void main(String[] args) {
EmpService empService = (EmpService)BeanFactory.getBean("empService");
empService.addEmp();
}
}
java中元注解(用来标识注解的注解)有四个:
@Target @Retention @Document @Inherited;
@Target:注解的作用目标
@Target(ElementType.TYPE) 可以作用在接口、类、枚举、注解
@Target(ElementType.FIELD) 字段、枚举的常量
@Target(ElementType.METHOD) 方法
@Target(ElementType.PARAMETER) 方法参数
@Target(ElementType.CONSTRUCTOR) 构造函数
@Target(ElementType.LOCAL_VARIABLE) 局部变量
@Target(ElementType.ANNOTATION_TYPE) 注解
@Target(ElementType.PACKAGE) 包
@Retention:注解的保留位置
@Retention(RetentionPolicy.SOURCE) 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
package Demo08104;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Bean {
public String id();//属性按照Java方法定义格式定义
}
package Demo08104;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Porperty {
public String value() default "";
public String ref() default "";
public int age() default 0;
}
package Demo08104;
@Bean(id="aaa")
public class Demo {
@Porperty(value ="admin")
private String name;
}
@Bean(id="a")
class A {
@Porperty(ref ="aaa",value ="")
private Demo demoid;
}
package Demo08104;
public class TestAnnotation {
public static void main(String[] args) throws Exception {
Map<String,Object> map = new HashMap<>();
Class<Demo> class1 =Demo.class;
if(class1.isAnnotationPresent(Bean.class)){
Bean bean = class1.getAnnotation(Bean.class);
System.out.println(bean.annotationType());
String id = bean.id();
System.out.println(id);
map.put(id,class1.newInstance());
}
Field field = class1.getDeclaredField("name");
field.setAccessible(true);
if(field.isAnnotationPresent(Porperty.class)){
Porperty porperty = field.getAnnotation(Porperty.class);
System.out.println(porperty.age());
System.out.println(porperty.ref());
System.out.println(porperty.value());
}
}
}