- XML
<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
DOM中所有结构都是节点(Node),包括:元素节点,属性节点,文本节点(回车也是文本节点)
元素节点(Element)中包含:属性节点,文本节点,子元素节点
<元素节点 属性节点>
文本节点
</元素节点>
- Parse
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"));
}
}
}
}
}
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦