java 读取和修改本地xml配置文件
求两个比较简单的方法就行了,能用就给分.一定要简单点,导包也没问题.xml如下:<?xmlversion="1.0"encoding="utf-8"standalone=...
求两个比较简单的方法就行了,能用就给分.一定要简单点,导包也没问题.
xml如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<DCPlusPlus>
<Settings>
<Nick type="string">lison02</Nick>
<UploadSpeed type="string">1000</UploadSpeed>
<DownloadDirectory type="string">D:\Downloads\</DownloadDirectory>
<Font type="string">宋体,-12,400,0</Font>
</Settings>
<Share>
<Directory Virtual="Downloads">D:\Downloads\</Directory>
</Share>
<NoShare/>
<PreviewApps/>
</DCPlusPlus> 展开
xml如下:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<DCPlusPlus>
<Settings>
<Nick type="string">lison02</Nick>
<UploadSpeed type="string">1000</UploadSpeed>
<DownloadDirectory type="string">D:\Downloads\</DownloadDirectory>
<Font type="string">宋体,-12,400,0</Font>
</Settings>
<Share>
<Directory Virtual="Downloads">D:\Downloads\</Directory>
</Share>
<NoShare/>
<PreviewApps/>
</DCPlusPlus> 展开
展开全部
dom4j解析
package demo;
import java.io.*;
import org.dom4j.*;
import org.dom4j.io.*;
import java.util.*;
public class WriteXML {
public void writer(){
//在内存中创建一个文档对象
Document doc=DocumentHelper.createDocument();
//往文档对象中添加一个元素
Element root=doc.addElement("users");
//将上面创建元素的设为根元素
doc.setRootElement(root);
//为根元素添加一个名称为user的子元素
Element user1=root.addElement("user");
//为user子元素添加一个id的属性 并赋值
user1.addAttribute("id","1");
//为user子元素添加一个子元素
Element name1=user1.addElement("name");
//为name子元素设置文本
name1.setText("zz");
Element config1=user1.addElement("config");
config1.setText("fullscreen");
Element user2=root.addElement("user");
//为user子元素添加一个id的属性 并赋值
user2.addAttribute("id","2");
//为user子元素添加一个子元素
Element name2=user2.addElement("name");
//为name子元素设置文本
name2.setText("xx");
Element config2=user2.addElement("config");
config2.setText("widescreen");
//下面将会进行输出产生XML文件
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
format.setIndent(true);
format.setNewLineAfterNTags(1);
format.setNewlines(true);
try {
XMLWriter writer=new XMLWriter(new FileOutputStream("users.xml"),format);
writer.write(doc);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
Element user2=user1.createCopy();
user2.attribute("id").setValue("2");
Iterator it=user2.elementIterator();
while(it.hasNext()){
it.next();
}*/
}
}
package demo;
import java.io.*;
import org.dom4j.*;
import org.dom4j.io.*;
import java.util.*;
public class WriteXML {
public void writer(){
//在内存中创建一个文档对象
Document doc=DocumentHelper.createDocument();
//往文档对象中添加一个元素
Element root=doc.addElement("users");
//将上面创建元素的设为根元素
doc.setRootElement(root);
//为根元素添加一个名称为user的子元素
Element user1=root.addElement("user");
//为user子元素添加一个id的属性 并赋值
user1.addAttribute("id","1");
//为user子元素添加一个子元素
Element name1=user1.addElement("name");
//为name子元素设置文本
name1.setText("zz");
Element config1=user1.addElement("config");
config1.setText("fullscreen");
Element user2=root.addElement("user");
//为user子元素添加一个id的属性 并赋值
user2.addAttribute("id","2");
//为user子元素添加一个子元素
Element name2=user2.addElement("name");
//为name子元素设置文本
name2.setText("xx");
Element config2=user2.addElement("config");
config2.setText("widescreen");
//下面将会进行输出产生XML文件
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
format.setIndent(true);
format.setNewLineAfterNTags(1);
format.setNewlines(true);
try {
XMLWriter writer=new XMLWriter(new FileOutputStream("users.xml"),format);
writer.write(doc);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
Element user2=user1.createCopy();
user2.attribute("id").setValue("2");
Iterator it=user2.elementIterator();
while(it.hasNext()){
it.next();
}*/
}
}
追问
你这个类好像只能写一个新的文件,不能修改其中的值,我需要一个方法,在参数输入名 和 值 来修改.而且这个类没有读的方法,希望能给一个好点的方法,谢谢.
解决问题追加100.
追答
我的方法是解析后在重组,不知道对你有没有用
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
你看一下这个吧.不需要导入特别的包,直接用API中的DOM方式解析,
并保存的.
-------------------------------------------------------------------------------------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class XmlApp extends JFrame implements ActionListener, ItemListener {
private JTextField textField;
private JComboBox comboBox;
private Map<String, String> content = null;
private Document doc;
private String file = "H:\\content.xml";
public XmlApp() {
getContentPane().setLayout(null);
comboBox = new JComboBox();
comboBox.setBounds(110, 10, 112, 21);
comboBox.addItemListener(this);
getContentPane().add(comboBox);
textField = new JTextField();
textField.setBounds(110, 41, 112, 21);
getContentPane().add(textField);
textField.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.setBounds(252, 40, 93, 23);
btnSave.addActionListener(this);
getContentPane().add(btnSave);
JLabel lblNode = new JLabel("Node");
lblNode.setBounds(10, 13, 90, 15);
getContentPane().add(lblNode);
JLabel lblValue = new JLabel("value");
lblValue.setBounds(10, 44, 90, 15);
getContentPane().add(lblValue);
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(400, 120);
setLocationRelativeTo(null);
setVisible(true);
}
public void init() {
content = new HashMap<String, String>();
DocumentBuilderFactory factory;
try {
factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(file);
loopNodes(doc.getFirstChild(), "", false);
textField.setText(content.get(comboBox.getSelectedItem()));
} catch (Exception e) {
System.out.println("e = " + e.getMessage());
}
}
public void loopNodes(Node node, String name, boolean isSave) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node tmp = list.item(i);
if (tmp instanceof Element) {
if (tmp.hasChildNodes()) {
loopNodes(tmp, tmp.getNodeName(), isSave);
}
}
if (tmp instanceof Text) {
String value = tmp.getNodeValue();
if (value != null && !"".equals(value.trim())) {
if (isSave) {
tmp.setNodeValue(content.get(name));
} else {
comboBox.addItem(name);
content.put(name, value.trim());
}
}
}
}
}
public static void main(String[] args) {
new XmlApp();
}
public void actionPerformed(ActionEvent e) {
String value = textField.getText();
content.put((String) comboBox.getSelectedItem(), value);
loopNodes(doc, "", true);
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
textField.setText(content.get(e.getItem()));
}
}
}
并保存的.
-------------------------------------------------------------------------------------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class XmlApp extends JFrame implements ActionListener, ItemListener {
private JTextField textField;
private JComboBox comboBox;
private Map<String, String> content = null;
private Document doc;
private String file = "H:\\content.xml";
public XmlApp() {
getContentPane().setLayout(null);
comboBox = new JComboBox();
comboBox.setBounds(110, 10, 112, 21);
comboBox.addItemListener(this);
getContentPane().add(comboBox);
textField = new JTextField();
textField.setBounds(110, 41, 112, 21);
getContentPane().add(textField);
textField.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.setBounds(252, 40, 93, 23);
btnSave.addActionListener(this);
getContentPane().add(btnSave);
JLabel lblNode = new JLabel("Node");
lblNode.setBounds(10, 13, 90, 15);
getContentPane().add(lblNode);
JLabel lblValue = new JLabel("value");
lblValue.setBounds(10, 44, 90, 15);
getContentPane().add(lblValue);
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(400, 120);
setLocationRelativeTo(null);
setVisible(true);
}
public void init() {
content = new HashMap<String, String>();
DocumentBuilderFactory factory;
try {
factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(file);
loopNodes(doc.getFirstChild(), "", false);
textField.setText(content.get(comboBox.getSelectedItem()));
} catch (Exception e) {
System.out.println("e = " + e.getMessage());
}
}
public void loopNodes(Node node, String name, boolean isSave) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node tmp = list.item(i);
if (tmp instanceof Element) {
if (tmp.hasChildNodes()) {
loopNodes(tmp, tmp.getNodeName(), isSave);
}
}
if (tmp instanceof Text) {
String value = tmp.getNodeValue();
if (value != null && !"".equals(value.trim())) {
if (isSave) {
tmp.setNodeValue(content.get(name));
} else {
comboBox.addItem(name);
content.put(name, value.trim());
}
}
}
}
}
public static void main(String[] args) {
new XmlApp();
}
public void actionPerformed(ActionEvent e) {
String value = textField.getText();
content.put((String) comboBox.getSelectedItem(), value);
loopNodes(doc, "", true);
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
textField.setText(content.get(e.getItem()));
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询