开始学习java处理xml--------jdom篇1

学习读取xml格式内容,为以后看框架代码打下基础

<?xml version="1.0" encoding="UTF-8"?>
<beans>
     <bean id="getUser" class="User">
          <propety id="UserDAO" ref="userDAO">        
          </propety>
     </bean>
      <bean id="getMsg" class="Msg">
          <propety id="msgDAO" ref="msgDAO">       
          </propety>
     </bean>
</beans>

 

package com.jdom.xml;

import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class JdomXml1 {
	public static void main(String[] args) {
		// 创建一个SAXBuilder对象
		SAXBuilder sax = new SAXBuilder();

		try {
			Document doc = sax.build(JdomXml1.class.getClassLoader()
					.getResource("test.xml"));

			Element root = doc.getRootElement();

			List<Element> beans = root.getChildren("bean");
			for (int i = 0; i < beans.size(); i++) {
				Element bean = beans.get(i);
				String id = bean.getAttribute("id").getValue();
				String classname = bean.getAttribute("class").getValue();
				System.out.println(bean.getName() + "--id--" + id
						+ "---class--" + classname);
				List<Element> propetys = bean.getChildren("propety");
				for (int j = 0; j < propetys.size(); j++) {
					Element propety = propetys.get(j);
					String pid = propety.getAttribute("id").getValue();
					String pclass = propety.getAttributeValue("ref");
					System.out.println(bean.getName() + "******--pid--" + pid
							+ "---class--" + pclass);
				}
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

} 

 xml文件格式如上

自己测试的java代码

 

结果:

bean--id--getUser---class--User
bean******--pid--UserDAO---class--userDAO
bean--id--getMsg---class--Msg
bean******--pid--msgDAO---class--msgDAO
 

 

 

 

你可能感兴趣的:(java)