How to insert/replace XML tag in XmlDocument?

I have a XmlDocument in java, created with the Weblogic XmlDocument parser.

I want to replace the content of a tag in this XMLDocument with my own data, or insert the tag if it isn’t there.

   <tag1 />
   <location />
   <tag3 />

For example I want to insert a URL in the location tag:


but otherwise leave the XML as is.

Currently I use a XMLCursor:

    XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
    XmlCursor xmlcur = xmlobj.newCursor();

    while (xmlcur.hasNextToken()) {
      boolean found = false;
      if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
        found = true;
      } else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
      } else if (xmlcur.isEnddoc()) {
        if (!found) {
          xmlcur.insertElementWithText("schema-location", "http://inserted");


I tried to find a “quick” xquery way to do this since the XmlDocument has an execQuery method, but didn’t find it very easy.

Do anyone have a better way than this? It seems a bit elaborate.


How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting.

If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following:

// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );

for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
  Node customDataNode = customDataNodeSet.item( i );

  // get the location nodes (if any) within this one customdata node
  NodeList locationNodeSet = findNodes(customDataNode, "location" );

  if (locationNodeSet.getLength() > 0) {
    // replace
    locationNodeSet.item( 0 ).setTextContent( "" );
  else {
    // insert
    Element newLocationNode = document.createElement( "location" );
    newLocationNode.setTextContent("" );
    customDataNode.appendChild( newLocationNode );

And here’s the helper method findNodes that does the XPath search.

private NodeList findNodes( Object obj, String xPathString )
  throws XPathExpressionException {

  XPath xPath = XPathFactory.newInstance().newXPath();
  XPathExpression expression = xPath.compile( xPathString );
  return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );