XML 和 Properties的相互转换

1.0 How to convert properties file into XML file – Java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    {
        Properties props = new Properties();
        props.setProperty("email.support", "[email protected]");

        //where to store?
        OutputStream os = new FileOutputStream("c:/email-configuration.xml");

        //store the properties detail into a pre-defined XML file
        props.storeToXML(os, "Support Email","UTF-8");

        System.out.println("Done");
    }
}

The above example will write the properties detail into a XML file “c:/email-configuration.xml“.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
        <comment>Support Email</comment>
        <entry key="email.support">[email protected]</entry>
    </properties>

2.0 How to convert XML file into properties file – Java

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
   <properties>
    <comment>Support Email</comment>
    <entry key="email.support">[email protected]</entry>
   </properties>
package com.mkyong;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesXMLExample
{
    public static void main(String[] args) throws IOException
    {
        Properties props = new Properties();

        InputStream is = new FileInputStream("c:/email-configuration.xml");
        //load the xml file into properties format
        props.loadFromXML(is);

        String email = props.getProperty("email.support");

        System.out.println(email);

    }
}

Output
The above example will print out the value of properties key : “email.support” :

donot-spam-me@nospam.com

  
xml在线校验、转JSON、格式化站点
https://codebeautify.org/xmlviewer

猜你喜欢

转载自blog.csdn.net/tb9125256/article/details/81212968