gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:56:24 25 4
gpt4 key购买 nike

如何使用 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();
}
}

}

最佳答案

这与您今天的其他问题有关吗?如果是,我认为您正在考虑将不应该复杂化的地方。

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);
}
}

关于java - 如何使用 Java 从属性 xml 中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com