2个回答
展开全部
public class BuildXML{
private static Properties props = new Properties();
static {
try {
props.load(Config.class.getClassLoader().getResourceAsStream("com/student/util/daoconfig.properties"));//properties文件路径
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
public static void buildXML(String fileName) {
Document doc = DocumentHelper.createDocument();
Element rootElmt = doc.addElement("properties");
//添加一个子节点示例
Element firstElmt = rootElmt.addElement("名字1");
firstElmt.setText(getProperty("名字1"));
firstElmt.addAttribute("属性名", "属性值");
outputXML(doc, fileName);
}
public static void outputXML(Document doc, String fileName) {
try {
FileWriter fw = new FileWriter(fileName);
OutputFormat foramt = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
XMLWriter xw = new XMLWriter(fw, format);
xw.write(doc);
xw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML示例:
<?xml version="1.0" encoding="gb2312"?>
<properties>
<名字1 属性名=“属性值”>名字1对应的值</名字1>
</properties>
需要引入DOM4j包。
private static Properties props = new Properties();
static {
try {
props.load(Config.class.getClassLoader().getResourceAsStream("com/student/util/daoconfig.properties"));//properties文件路径
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
public static void buildXML(String fileName) {
Document doc = DocumentHelper.createDocument();
Element rootElmt = doc.addElement("properties");
//添加一个子节点示例
Element firstElmt = rootElmt.addElement("名字1");
firstElmt.setText(getProperty("名字1"));
firstElmt.addAttribute("属性名", "属性值");
outputXML(doc, fileName);
}
public static void outputXML(Document doc, String fileName) {
try {
FileWriter fw = new FileWriter(fileName);
OutputFormat foramt = OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
XMLWriter xw = new XMLWriter(fw, format);
xw.write(doc);
xw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
XML示例:
<?xml version="1.0" encoding="gb2312"?>
<properties>
<名字1 属性名=“属性值”>名字1对应的值</名字1>
</properties>
需要引入DOM4j包。
追问
运用所学java.util的知识,写出一个读取配置文件(myclass.properties) 的程序,并 把信息转化为 xml 格式,内容如下:
className=杭师大Java班
studentConts=30
teamConts=6
。。。。刚太急没注意问题。。。能麻烦在指导一下吗
追答
Element firstElmt = rootElmt.addElement("className1");
firstElmt.setText(getProperty("杭师大Java班"));
Element firstElmt = rootElmt.addElement("studentConts");
firstElmt.setText(getProperty("30"));
Element firstElmt = rootElmt.addElement("teamConts");
firstElmt.setText(getProperty("6"));
outputXML(doc, fileName);
只要把添加一个子节点示例修改完上面代码即可
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询