使用Properties加载一般属性文件(key-name=value),非常方便,
但是如何使用Properties加载XML中定义的属性?这种加载方式海选XML文件还需要特殊的格式吗?非常感谢!

解决方案 »

  1.   

    use loadFromXML(InputStream in) method of Properties to have a try
      

  2.   

    有DTD定义。你导出一个Properties到xml文件看看就明白了
      

  3.   

    没办法,用SAX解析吧,不过用Properties存储会覆盖重复的属性哦.import java.io.FileInputStream;
    import java.util.Properties;import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    public class MyXmlProperitiesLoader { /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    SAXParserFactory spf = SAXParserFactory.newInstance(); 
    SAXParser parser=spf.newSAXParser();
    MyContentHandler handler=new MyContentHandler();
    parser.parse(new FileInputStream("Sessions.xml"),handler);
    Properties prop=handler.getProp();
    System.out.println(prop);
    }}class MyContentHandler extends DefaultHandler{

    private Properties prop;

    public Properties getProp() {
    return prop;
    } public MyContentHandler() {
    // TODO Auto-generated constructor stub
    prop=new Properties();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
    Attributes attributes) throws SAXException {
    // TODO Auto-generated method stub
    for(int i=0;i<attributes.getLength();i++){
    super.startElement(uri, localName, qName, attributes);
    System.out.println(attributes.getLocalName(i)+":"+attributes.getValue(i));
    prop.put(attributes.getLocalName(i), attributes.getValue(i));
    }
    }
    }
      

  4.   


    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
    <entry key="id">00001</entry>
    </properties>  public static void main(String[] args) throws Exception {
          InputStream in = new FileInputStream("properties.xml");
          Properties p = new Properties();
          p.loadFromXML(in);
          in.close();
          System.err.println(p.getProperty("id"));
       }