java读取XML文件

1.读取XML文件的类:

public class XMLUtils { private final String DB_XML_FILE = "/XMLSetting.xml"; public Properties getPropertiesFromXML() { URL url = XMLUtils.class.getResource(dBXMLFILE); URI uri; try { uri = url.toURI(); InputSource xmlfile = new InputSource(uri.getPath()); MyDefaultHandler handler = new MyDefaultHandler (); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); parser.parse(xmlfile, handler); return handler.getProps(); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); return null; } catch (SAXException e) { System.out.println(e.getMessage()); return null; } catch (IOException e) { System.out.println(e.getMessage()); return null; } catch (URISyntaxException e) { System.out.println(e.getMessage()); return null; } } }

2.处理XML文件的类:

import java.util.Properties; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.app.common.Constants; public class MyDefaultHandler extends DefaultHandler { private Properties props; private String key = ""; private StringBuffer value = new StringBuffer(); public MyDefaultHandler() { props = new Properties(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { value.append(ch, start, length); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { props.put(key, value.toString().trim()); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { value.delete(0, value.length()); key = attributes.getValue(Constants.KEY); } public Properties getProps() { return this.props; } }

 

3.main:

import java.util.Properties; public class TestMain { private static Properties properties = null; /** * @param args */ public static void main(String[] args) { XMLUtils utils = new XMLUtils(); properties = utils.getPropertiesFromXML(); if (properties != null) { System.out.println(properties.getProperty("key1")); System.out.println(properties.getProperty("key2")); System.out.println(properties.getProperty("key3")); } } }

你可能感兴趣的:(java,xml,properties,String,null,attributes)