就是这个方法
//修改某个Element的值
//如果该Element不存在,则先添加
//参数说明:
//doc org.jdom.Document 被修改的xml对象
//xpath java.lang.String 想要修改的Element路径,采用“xxx/xxx/xxx”的形式
//value java.lang.String 想要修改的Element的值
//注:本方法为demo,没有涉及任何异常处理
public void modifyElement(Document doc, String xpath, String value) throws JDOMException {
String[] pathes = xpath.split("/");
Element tempEle = null;
String path = null;
for (int i = 0; i < pathes.length; i++) {
path = pathes[i];
if (tempEle == null) {
tempEle = (Element) XPath.selectSingleNode(doc.getRootElement(), "//" + path);
if (tempEle == null) {
tempEle = new Element(path);
doc.getRootElement().addContent(tempEle);
}
} else if (tempEle.getChild(path) != null) {
tempEle = tempEle.getChild(path);
} else {
tempEle.addContent(new Element(path));
tempEle = tempEle.getChild(path);
}
}
tempEle.setText(value);
}
更新不了xml文件。
//修改某个Element的值
//如果该Element不存在,则先添加
//参数说明:
//doc org.jdom.Document 被修改的xml对象
//xpath java.lang.String 想要修改的Element路径,采用“xxx/xxx/xxx”的形式
//value java.lang.String 想要修改的Element的值
//注:本方法为demo,没有涉及任何异常处理
public void modifyElement(Document doc, String xpath, String value) throws JDOMException {
String[] pathes = xpath.split("/");
Element tempEle = null;
String path = null;
for (int i = 0; i < pathes.length; i++) {
path = pathes[i];
if (tempEle == null) {
tempEle = (Element) XPath.selectSingleNode(doc.getRootElement(), "//" + path);
if (tempEle == null) {
tempEle = new Element(path);
doc.getRootElement().addContent(tempEle);
}
} else if (tempEle.getChild(path) != null) {
tempEle = tempEle.getChild(path);
} else {
tempEle.addContent(new Element(path));
tempEle = tempEle.getChild(path);
}
}
tempEle.setText(value);
}
更新不了xml文件。
我还以为有什么好事呢---------------------------
“写入再读出,显示的是更改后的,但是直接打开文件,显示的是更改前的,这是为什么??”
---------------------------
我没看懂你的操作过程
但我认为的正确的过程应该是:
读xml->生成jdom的Document对象->修改(传递正确的参数给modifyElement方法)->将该Document对象写回xml文件中也许这就是你所谓的写入再读出吧
“直接打开文件”是什么样的操作,我不是很明白
如果你对修改的结果不很确定的话
也可以把修改后Document转化成String打印到后台,检查一下是否正确good luck!
但是直接双击,打开(或者用工具打开)显示的内容没有改变(是没有修改前的)。
这是为什么??
^_^
那只是修改了内存中的Document对象
你最终还得把这个写回到xml文件中啊