[jdom-interest] newbie question: save changes to document

Bradley S. Huffman hip at a.cs.okstate.edu
Wed Jun 1 18:54:41 PDT 2005


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


More information about the jdom-interest mailing list