XML解析工具以及Properties文件解析工具

XML文件解析

  1. xml的标签之间,存在着明显的一对多的关系,是一种“树形解析器”,我们通过代码来解析出xml文件中的某些属性对应的值。

看一段xml,我们对其进行解析:``

<?xml version="1.0" encoding="UTF-8"?>
<animals>
<animal  id ="1"  name="湘子" color="红">
	<hobbies>
	   <hobby>爱说话</hobby>
	   <hobby>书画</hobby>
	   <hobby>特爱说话</hobby>
	   <hobby>非常跳</hobby>
	</hobbies>
</animal>

<animal  id ="2" name="丁丁" color="黄">
	<hobbies>
	   <hobby>喜多</hobby>
	   <hobby>书画</hobby>
	   <hobby>戏份多</hobby>
	 
	</hobbies>
</animal>

<animal  id ="3"  name="钉钉" color="黑">
	<hobbies>
	   <hobby>嘎画</hobby>
	   <hobby>特爱说话</hobby>
	   <hobby>爱演戏</hobby>
	   <hobby>骗人</hobby>
	</hobbies>
</animal>

</animals>
public class Demo {

	
	public static void main(String[] args) {
		
		try {
			//巫师的咒语 记住
			DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
			DocumentBuilder db=dbf.newDocumentBuilder();
			
			InputStream is =Class.class.getResourceAsStream("/Animal.xml");
			System.out.println(is);
			try {
				org.w3c.dom.Document document=db.parse(is);
				System.out.println(is);
				//取标签名为“animal”的标签    并建立一个NodeList 来存
				NodeList animalList=document.getElementsByTagName("animal");
				//遍历
				for(int index=0; index<animalList.getLength();index++) {
					//属性的查找方法
					Element animal=(Element)animalList.item(index);
					String id=animal.getAttribute("id");
					String name=animal.getAttribute("name");
					System.out.println("动物的编号"+id+""+name);
					//字标签的查找方法
					NodeList hobbies =animal.getElementsByTagName("hobbies");
					for(int i=0;i<hobbies.getLength();i++) {
						Element hobbyTag=(Element)hobbies.item(i);
						String  hobby =hobbyTag.getTextContent();
						System.out.println("\t"+hobby);
							
					}
				}
				
				
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
	
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}

}

  • 只是实现这样的功能实在是甘心,每次解析还要输入xml的路径名字,等所以想着做成一个工具,这个工具有静态块,动态块之分,静态块在第一次实例化这个对象时被执行,以后不再执行。这里将parse(InputStream)写成一个方法。将固定的几步定死,把需要用户提供的怎样提取值等的方法做成抽象的,让用户在使用工具时,自己来编写。
public abstract class XMLParser {
	private static DocumentBuilder db;
	
	static {
		try {
			db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public XMLParser() {
	}
	
	public static Document loadXml(String xmlPath) throws SAXException, IOException {
		InputStream is = XMLParser.class.getResourceAsStream(xmlPath);
		return loadXml(is);
	}
	
	public static Document loadXml(InputStream is) throws SAXException, IOException {
		return db.parse(is);
	}
	
	public abstract void dealElement(Element element, int index);
	//用户自行实现1
	
	public void parse(Document document, String tagname) {
		NodeList nodeList = document.getElementsByTagName(tagname);
		for (int index = 0; index < nodeList.getLength(); index++) {
			Element element = (Element) nodeList.item(index);
			dealElement(element, index);
		}
	}
	
	public void parse(Element element, String tagname) {
		NodeList nodeList = element.getElementsByTagName(tagname);
		for (int index = 0; index < nodeList.getLength(); index++) {
			Element ele = (Element) nodeList.item(index);
			dealElement(ele, index);
		}
	}
	
}

我们来看看这个对这个工具类的调用来进行文件的解析有多磨方便吧哈哈。

public class Test {

	public static void main(String[] args) {
		XMLParser parser =new XMLParser() {

			public void parseElement(Element element, int index) {
				String id =element.getAttribute("id");
				System.out.println("编号"+id);
			}

		
		};

		try {
			Document document = parser.loadXml("/Animal.xml");
			parser.parse(document,"animal");
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}

是不是很高效呢呵呵,虽然是很简单的,但确实是做出来了一个有普适性和实用性的简单工具。

  1. Properties文件是键值对组成的,咱们来看看他的解析吧
public class PripertitiesParser {

	public static void main(String[] args) {
		
		try {
			//巫师的咒语,要记住
			Properties properties =new Properties();
			InputStream  is=Class.class.getResourceAsStream("/config.properties");
			properties.load(is);
			
			Enumeration<Object> keys =properties.keys();
			//Enumerations 是一个泛型类,里面储存键值对数据集合:
			//这步是来获取文件中的键集合
			//遍历一下
			while(keys.hasMoreElements()) {
				String key=(String) keys.nextElement();
				String value=properties.getProperty(key);
				System.out.println(key+"  "+value);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	
	}

}

有相应的注释看起来应该是特别简单的。

我们来看看properties文件的实用性吧,他可以作为一个配置文件,比如一个程序运行刚开始,得先执行一个“初始化功能的问题”,这就必须得从配置文件之中进行读取,而不是让用户输入

接下来看一个实例,这里面做成了一个工具,并且,将键值对用HashMap存了下来。

public class CGFParser {
	public static final Map<String,String> configMap;
	static {
		configMap=new HashMap<>();
	}
	public CGFParser() {
	}
	public static void readConfig(String configFilePath) throws IOException {
		InputStream is=Class.class.getResourceAsStream(configFilePath);
		
		Properties properties=new Properties();
		properties.load(is);
		
		Enumeration<Object> keySet =properties.keys();
		while(keySet.hasMoreElements()) {
			String key=(String) keySet.nextElement();
			String value=properties.getProperty(key);
			configMap.put(key, value);
		}
		}
		
		public static String value(String key) {
			return configMap.get(key);
	}
	//这个方法让用户调用,用来给想要初始化的东西解析出来进行赋值!
	

代码复用性大大增加!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值