View Javadoc

1   /*
2    * $Id: XPathNodeExpressionEvaluator.java 21676 2011-04-09 19:12:32Z dirk.olmes $
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      @Override
46      protected Object extractResultFromNode(Object result)
47      {
48          if (result instanceof Element)
49          {
50              ((Element) result).detach();
51              return DocumentHelper.createDocument((Element) result);
52          }
53          else if (result instanceof org.w3c.dom.Element)
54          {
55              return extractW3CElement(result);
56          }
57          else
58          {
59              return result;
60          }
61      }
62  
63      protected Object extractW3CElement(Object result)
64      {
65          org.w3c.dom.Element element = (org.w3c.dom.Element) result;
66  
67          Document doc = builder.newDocument();
68          doc.appendChild(doc.importNode(element, true));
69          return doc;
70      }
71  
72      /**
73       * {@inheritDoc}
74       */
75      @Override
76      public String getName()
77      {
78          return NAME;
79      }
80  }