View Javadoc

1   /*
2    * $Id: XPathNodeExpressionEvaluator.java 20321 2010-11-24 15:21:24Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.xml.expression;
12  
13  import org.mule.api.expression.ExpressionRuntimeException;
14  import org.mule.module.xml.i18n.XmlMessages;
15  
16  import javax.xml.parsers.DocumentBuilder;
17  import javax.xml.parsers.DocumentBuilderFactory;
18  import javax.xml.parsers.ParserConfigurationException;
19  
20  import org.dom4j.DocumentHelper;
21  import org.dom4j.Element;
22  import org.w3c.dom.Document;
23  
24  /**
25   * Will select the text of a single node based on the property name
26   */
27  public class XPathNodeExpressionEvaluator extends XPathExpressionEvaluator
28  {
29      public static final String NAME = "xpath-node";
30  
31      private DocumentBuilder builder;
32  
33      public XPathNodeExpressionEvaluator()
34      {
35          try
36          {
37              builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
38          }
39          catch (ParserConfigurationException e)
40          {
41              throw new ExpressionRuntimeException(XmlMessages.failedToCreateDocumentBuilder(), e);
42          }
43      }
44  
45      protected Object extractResultFromNode(Object result)
46      {
47          if (result instanceof Element)
48          {
49              ((Element) result).detach();
50              return DocumentHelper.createDocument((Element) result);
51          }
52          else if (result instanceof org.w3c.dom.Element)
53          {
54              Document doc = builder.newDocument();
55              doc.appendChild((org.w3c.dom.Element) result);
56              return doc;
57          }
58          else
59          {
60              return result;
61          }
62      }
63  
64      /**
65       * {@inheritDoc}
66       */
67      public String getName()
68      {
69          return NAME;
70      }
71  }