如何使用Java从属性xml获取值?

时间:2017-11-30 12:46:30

标签: java xml properties

如何使用Java从属性xml获取值?

我需要使用我列出的java方法获取具有key = password的元素的值,反过来Helllo123应该输出到控制台窗口。

属性XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Properties Example</comment>
<entry key="myvoucherDummySearchTerm">www.example.com</entry>
<entry key="password">Hello123</entry>
</properties>

JAVA方法:

public class ChangeToXml {

    public static void main(String[] args) throws IOException {
        Properties p = new Properties();
        FileInputStream fi = new FileInputStream(Base_Page.getConstant(Constant.CONFIG_PROPERTIES_DIRECTORY));
        p.load(fi);

        FileOutputStream fos = new FileOutputStream("properties.xml");
        p.storeToXML(fos, "Properties Example");

        testMethod();
    }

    public static void testMethod() {

        try {

        File fXmlFile = new File("C://Users//joe.blogs//Desktop//AutoFramework//AutoFramework//properties.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("staff");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;
                System.out.println("Staff id : " + eElement.getElementsByTagName("password").item(0).getTextContent());
            }
        }
        } catch (Exception e) {
        e.printStackTrace();
        }
      }

}

4 个答案:

答案 0 :(得分:1)

这是否与您今天的其他问题有关?如果是的话,我认为你在考虑复杂的地方。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class ChangeToXml {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties p = new Properties();
        //load from your original file;
        FileInputStream inputProps = new FileInputStream("C:\\tmp\\config.properties");
        p.load(inputProps);
        //store in xml format
        FileOutputStream outputXml = new FileOutputStream("C:\\tmp\\properties.xml");
        p.storeToXML(outputXml, "Properties Example");
        //load from xml
        FileInputStream inputXml = new FileInputStream("C:\\tmp\\properties.xml");
        p.loadFromXML(inputXml);
        // get key value pair in the same way as from your original file
        String browser = p.getProperty("browser");
        String url = p.getProperty("url");

        System.out.println("browser: " + browser);
        System.out.println("url: " + url);
    }
}

答案 1 :(得分:0)

我建议您实施解决方案SAX解析器。 SAX解析器是XML文档的基于事件的解析器。

答案 2 :(得分:0)

你可以这样做

try {
        File file = new File("test.xml");
        FileInputStream fileInput = new FileInputStream(file);
        Properties properties = new Properties();
        properties.loadFromXML(fileInput);
        fileInput.close();

        Enumeration enuKeys = properties.keys();
        while (enuKeys.hasMoreElements()) {
            String key = (String) enuKeys.nextElement();
            String value = properties.getProperty(key);
            System.out.println(key + ": " + value);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 3 :(得分:0)

您可以使用正则表达式在xml中解析 所以这将有助于你

 public static void main(String[] args) throws IOException {
            String content = new String(Files.readAllBytes(Paths.get("properties.xml")));
            System.out.println(Arrays.toString(getTagValues(content).toArray())); // Prints [Hello123]
        }

        private static final Pattern TAG_REGEX = Pattern.compile("<entry key=\"password\">(.+?)</entry>");

        private static List<String> getTagValues(final String str) {
            final List<String> tagValues = new ArrayList<String>();
            final Matcher matcher = TAG_REGEX.matcher(str);
            while (matcher.find()) {
                tagValues.add(matcher.group(1));
            }
            return tagValues;
        }