xml读取

1、首先得到xml路径:

      String xmlurl=ReadConfigXml.class.getResource("").getPath().replace("/WEB-INF/classes/com/common", "")+ "global/xml/dataConn.xml";

2、决定解析xml文件的方式,例如选择SAX方法:

  //获取SAX工厂对象
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setValidating(false);
  //获取SAX解析
  SAXParser parser = factory.newSAXParser();
  File f = new File(filename);
  DefaultHandler handler = new DefaultHandler();  //此处使用默认的解析器
  parse.parse(f,handler); 
 
  如果此处使用其他解析器,必须继承DefaultHandler类。重写DefaultHandler类的startElement、characters、endElement方法。

  具体完整代码如下:
  class ConfigParser extends DefaultHandler {

////定义一个Properties 用来存放属性值
private Properties props;

private String currentSet;
private String currentName;
private StringBuffer currentValue = new StringBuffer();

//构建器初始化props
public ConfigParser() {

this.props = new Properties();
}

public Properties getProps() {
return this.props;
}

//定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
currentValue.delete(0, currentValue.length());
this.currentName =qName;
}

//这里是将<xxx></xxx>之间的值加入到currentValue
public void characters(char[] ch, int start, int length) throws SAXException {
currentValue.append(ch, start, length);
}

//在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中
public void endElement(String uri, String localName, String qName) throws SAXException {
props.put(qName.toLowerCase(), currentValue.toString().trim());
}

}

class ParseXML{
//定义一个Properties 用来存放属性值
private Properties props;

public Properties getProps() {
return this.props;
}

public void parse(String filename) throws Exception {
//将我们的解析器对象化
ConfigParser handler = new ConfigParser();
//获取SAX工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
//获取SAX解析
SAXParser parser = factory.newSAXParser();
try{
//将解析器和解析对象xml联系起来,开始解析
parser.parse(new java.io.File(filename),handler);
//获取解析成功后的属性
props = handler.getProps();

}finally{
factory=null;
parser=null;
handler=null;
}
}
}
//读取系统Config信息
public class ReadConfigXml
{
private Properties props;

public ReadConfigXml(){
ParseXML myRead = new ParseXML();
try {
    String xmlurl=ReadConfigXml.class.getResource("").getPath().replace("/WEB-INF/classes/com/common", "")+ "global/xml/dataConn.xml";
myRead.parse(xmlurl);
props = new Properties();
props = myRead.getProps();
} catch (Exception e) {
e.printStackTrace();
}
}

  public String get(String Name){
    return props.getProperty(Name);
  }
  public static void main(String[] g){
  ReadConfigXml r = new ReadConfigXml();
  r.get("txtfiledir");
}
}

你可能感兴趣的:(xml,Web,F#)