[jdom-interest] newbie question: save changes to document
graste
graste at gmail.com
Thu Jun 2 05:51:06 PDT 2005
Am Thu, 02 Jun 2005 03:54:41 +0200 schrieb Bradley S. Huffman
<hip at cs.okstate.edu>:
> graste writes:
>
>> I have a question about saving changes to elements into an existing
>> document. I retrieve an element using a simple xpath expression. After
>> that I modify the element and want to write the changes back to the
>> original document. How can I do this?
>>
>> // code parts stripped (exception handling etc.)
>>
>> String xpath = "/path/to/some/element";
>> Document document = builder.build(new File(pathToFile));
>> Element elem = (Element) XPath.selectSingleNode(document, xpath); // get
>> element
>> elem.getChild("someElem").setText("someContent"); // do some
>> modifications
>>
>> // somehow save changes here
>>
>> XMLOutputter outp = new XMLOutputter(Format.getCompactFormat()); //
>> write
>> document
>> outp.output(document, new FileOutputStream(new File(pathToFile))); //
>> back
>> to disk
>>
>> Any suggestions to a JDom newbie? I'm using the latest JDom version and
>> have no problems reading different XML files.
>
> Use more XPath.
>
> Document document = builder.build(new File(pathToFile));
>
> // Select first someElem in document
> String xpath = "/path/to/some/element/someElem[1]";
> Element someElem = (Element) XPath.selectSingleNode(document, xpath);
>
> // Do modification
> if (someElem != null) {
> someElem.setText("someContent"); // do some modifications
> }
> else {
> // didn't find what you wanted, take appropriate action
> }
>
> Brad
Thanks, that helps. Even if I don't _really_ understand why, I'm now able
to change my code according to your help.
Regards,
Steffen
More information about the jdom-interest
mailing list