Привет, коллеги-программисты :).Java добавить элемент с атрибутами в xml-файл
Я очень новичок в Java, и если это был PHP, я уже сделал это: P, в любом случае я попытался найти здесь все ответы (stackoverflow), но ни одна не соответствует моей конкретной проблеме, или я не видел например, или я пропустил что-то ... в любом случае, напишите ссылки на ответы, если вы знаете какое-либо решение, подобное моей проблеме.
Ok проблемы;)
У меня есть этот 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