<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="wheel" class="com.titizz.simulation.toyspring.Wheel">
<property name="brand" value="Michelin" />
<property name="specification" value="265/60 R18" />
</bean>
<bean id="car" class="com.titizz.simulation.toyspring.Car">
<property name="name" value="Mercedes Benz G 500"/>
<property name="length" value="4717mm"/>
<property name="width" value="1855mm"/>
<property name="height" value="1949mm"/>
<property name="wheel" ref="wheel"/>
</bean>
</beans>
DOM中所有结构都是节点(Node),包括:元素节点,属性节点,文本节点(回车也是文本节点)
元素节点(Element)中包含:属性节点,文本节点,子元素节点
<元素节点 属性节点>
文本节点
</元素节点>
public class ParseTest {
@Test
public void testParseDOM() throws Exception {
URL url = ParseTest.class.getClassLoader().getResource("toy-spring-ioc.xml");
System.out.println(url);
String location = url.getFile();
System.out.println(location);
// 加载 xml 配置文件
InputStream inputStream = new FileInputStream(location);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.parse(inputStream);
Element rt = doc.getDocumentElement();
System.out.println(rt.getTagName());
System.out.println("-----------------------------------------------");
/*
* DOM中所有结构都是节点,包括:元素节点,属性节点,文本节点(回车也是文本节点)
* 元素节点中包含:属性节点,文本节点,子元素节点
*
* Node:节点
* Element:元素节点
*
* */
NodeList nodes = rt.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
//文本节点
if (node instanceof Text){
Text text = (Text) node;
System.out.println(text.getWholeText());
}
//元素节点
if(node instanceof Element){
Element ele = (Element) node;
System.out.println(ele.getTagName());
System.out.println("id : " + ele.getAttribute("id"));
System.out.println("class : " + ele.getAttribute("class"));
//子元素节点
NodeList properties = ele.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node propertyNode = properties.item(j);
if(propertyNode instanceof Element){
Element property = (Element) propertyNode;
System.out.print(property.getAttribute("name") + " : ");
if (property.hasAttribute("value")) {
System.out.println(property.getAttribute("value"));
}else if (property.hasAttribute("ref")){
System.out.println(property.getAttribute("ref"));
}
}
}
}
}
}
}
打开App,阅读手记