你好同行的程序员:)。我是非常新的Java,如果这是PHP我已经这样做:P,无论如何,我试图在这里搜索所有答案(stackoverflow),但没有一个适合我的具体问题,或者我没有看到一个例如,我错过了某些东西......无论如何,如果你知道任何类似于我的问题的解决方案,请张贴链接到答案。Java添加元素的属性到xml文件
确定的问题;)
我有这样的XML文件中的,我需要它,就像这样:
<?xml version="1.0" encoding="UTF-8"?>
<events>
<event id="46" title="Ferias" start="2013-04-25" end="2013-04-26" allDay="false" editable="true"/>
<event id="47" title="Falta" start="Wed Apr 17 2013 00:00:00 GMT+0100" end="Thu Apr 18 2013 00:00:00 GMT+0100" allDay="false" editable="true"/>
<event id="48" title="Tolerancia de Ponto" start="Mon Apr 01 2013 00:00:00 GMT+0100" end="" allDay="false" editable="true"/>
<event id="49" title="Titulo teste" start="Thu Apr 11 2013 00:00:00 GMT+0100" end="Sat Apr 13 2013 00:00:00 GMT+0100" allDay="true" editable="true"/>
<event id="50" title="dfgfdgf" start="Fri Apr 12 2013 00:00:00 GMT+0100" end="Sat Apr 13 2013 00:00:00 GMT+0100" allDay="true" editable="true"/>
<event id="51" title="hghfjfghj" start="Tue Apr 16 2013 00:00:00 GMT+0100" end="Wed Apr 17 2013 00:00:00 GMT+0100" allDay="true" editable="true"/>
<event id="52" title="grande evento" start="Tue Apr 23 2013 00:00:00 GMT+0100" end="Wed May 01 2013 00:00:00 GMT+0100" allDay="true" editable="true"/>
</events>
,我尝试添加新的元素“事件”与atributes,我用这个来加载和修改:
String FilePath = "D:/myxml.xml";
Document doc = openXMLfile(FilePath);
其未装入这里的问题..
,其中openXMLfile是这样的:
protected Document openXMLfile(String filepath){
Document doc = null;
try {
File fXmlFile = new File(filepath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(fXmlFile);
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
然后在我的函数添加元素我这样做:
File file = new File("D:\myxml.xml");
Element event = doc.createElement("event");
event.setAttribute("test","testvalue");
doc.getDocumentElement().appendChild(event);
filePutContents(doc,file);
其中filePutContents我有这样的功能:
protected void filePutContents(Document doc,File file){
try{
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,"yes");
DOMSource source = new DOMSource(doc);
//StreamResult result = new StreamResult(System.out);//problem was this
StreamResult result = new StreamResult(file);//correct way
transformer.transform(source, result);
}catch(TransformerConfigurationException tce){
/*ERRO do Transformer*/
System.out.println("* Transformer Factory error");
System.out.println(" " + tce.getMessage());
Throwable x = tce;
if (tce.getException() != null)
x = tce.getException();
x.printStackTrace();
}catch(TransformerException te){
/*ERRO da Factory*/
System.out.println("* Transformation error");
System.out.println(" " + te.getMessage());
Throwable x = te;
if (te.getException() != null)
x = te.getException();
x.printStackTrace();
}
}
的问题是,没有元素被添加到文件中,我希望文件被更新,我做错了什么?谢谢
代码问题解决了,我反映的变化;)谢谢做佣工:)
问题是什么? – Kishore 2013-04-22 10:36:49