什么是配置文件?
配置文件 xxx.properties(解决硬编码)–>写死又重复修改的代码
xml文件:
语法格式:
第一行固定写法,注意utf-8
标签:<>表示,可以嵌套,但是不能交叉嵌套
标签是成对存在的,又开始标签必须要有结束标签<></>
如果没有子标签,一般使用但标签<name/>
严格区分大小写
结构:
是一个树状结构
从上到下每一个节点都可以拿到
Element来表示标签
属性用Attr
文本呢 Text
会寻找节点,从根节点出发:xxx.getDocumentElement()
getElementsByTagName("xxxx")
Document--->DocumentBuilder---->DocumentBuilderFactory--->newInstace
注意:xml文件的路径一般使用相对路径,新建resource炸药包文件夹,配置文件一般放这里
文件的输入流使用 Thread类中的current....方法
配置文件:解决硬编码
不用引号
不用空格
使用xml文件获取信息时注意:
1.文件路径(相对路径--->resource file)
2.获取节点后的强转...item(index)
3.清楚xml的结构(树状)-->通过父节点获取子节点
演示
public void xmldemo2() throws Exception {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml");
// 获取document
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
// 获取根节点
Element rootele = doc.getDocumentElement();
// 从根节点下获取所有子节点
NodeList sspropertyList = rootele.getElementsByTagName("student");
// 遍历子节点 获取每一个节点(student)
for (int j = 0; j < sspropertyList.getLength(); j++) {
// 获取学生节点
Element stuele = (Element) rootele.getElementsByTagName("student").item(j);
// 获取类的全限定名
String className = stuele.getAttribute("class");
// 创建对象
Object obj = Class.forName(className).newInstance();
// 拿到该节点下的各个属性(子节点)
NodeList propertyList = stuele.getElementsByTagName("property");
// 遍历student下的所有子节点(property)
for (int i = 0; i < propertyList.getLength(); i++) {
// 获取属性(property)节点
Element stu = (Element) propertyList.item(i);
// 获取name的值
String propertiesName = stu.getAttribute("name");
// 获取value的值
String propertiesValue = stu.getAttribute("value");
// 内省student
PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass(), Object.class)
.getPropertyDescriptors();
// 封装
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
Method method = pd.getWriteMethod();
if (name.equals(propertiesName)) {
method.invoke(obj, propertiesValue);
}
}
}
System.out.println(obj);
}
}
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<contain>
<student id="01" class="com.classproperties.Student">
<property name="name" value="那个男人" />
<property name="age" value="2" />
<property name="favourite" value="It is me" />
<property name="address" value="广州" />
</student>
<student id="02" class="com.classproperties.Student">
<property name="name" value="就是我"></property>
<property name="age" value="8"></property>
<property name="favourite" value="xxx"></property>
<property name="address" value="广州"></property>
</student>
</contain>