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