org.w3c.dom.Text Java Examples

The following examples show how to use org.w3c.dom.Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMLSignature.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Base64 encodes and sets the bytes as the content of the SignatureValue
 * Node.
 *
 * @param bytes bytes to be used by SignatureValue before Base64 encoding
 */
private void setSignatureValueElement(byte[] bytes) {

    while (signatureValueElement.hasChildNodes()) {
        signatureValueElement.removeChild(signatureValueElement.getFirstChild());
    }

    String base64codedValue = Base64.encode(bytes);

    if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
        base64codedValue = "\n" + base64codedValue + "\n";
    }

    Text t = this.doc.createTextNode(base64codedValue);
    signatureValueElement.appendChild(t);
}
 
Example #2
Source File: AbstractMarshallerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void marshalEmptyDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	DOMResult domResult = new DOMResult();
	marshaller.marshal(flights, domResult);
	assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document);
	Document result = (Document) domResult.getNode();
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
Example #3
Source File: Base64.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method decode
 *
 * Takes the <CODE>Text</CODE> children of the Element and interprets
 * them as input for the <CODE>Base64.decode()</CODE> function.
 *
 * @param element
 * @return the byte obtained of the decoding the element
 * $todo$ not tested yet
 * @throws Base64DecodingException
 */
public static final byte[] decode(Element element) throws Base64DecodingException {

    Node sibling = element.getFirstChild();
    StringBuffer sb = new StringBuffer();

    while (sibling != null) {
        if (sibling.getNodeType() == Node.TEXT_NODE) {
            Text t = (Text) sibling;

            sb.append(t.getData());
        }
        sibling = sibling.getNextSibling();
    }

    return decode(sb.toString());
}
 
Example #4
Source File: DOMBuilder.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Receive notification of character data.
 *
 * <p>The Parser will call this method to report each chunk of
 * character data.  SAX parsers may return all contiguous character
 * data in a single chunk, or they may split it into several
 * chunks; however, all of the characters in any single event
 * must come from the same external entity, so that the Locator
 * provides useful information.</p>
 *
 * <p>The application must not attempt to read from the array
 * outside of the specified range.</p>
 *
 * <p>Note that some parsers will report whitespace using the
 * ignorableWhitespace() method rather than this one (validating
 * parsers must do so).</p>
 *
 * @param ch The characters from the XML document.
 * @param start The start position in the array.
 * @param length The number of characters to read from the array.
 * @see #ignorableWhitespace
 * @see org.xml.sax.Locator
 */
public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
{
  if(isOutsideDocElem()
     && com.sun.org.apache.xml.internal.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
    return;  // avoid DOM006 Hierarchy request error

  if (m_inCData)
  {
    cdata(ch, start, length);

    return;
  }

  String s = new String(ch, start, length);
  Node childNode;
  childNode =  m_currentNode != null ? m_currentNode.getLastChild(): null;
  if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
     ((Text)childNode).appendData(s);
  }
  else{
     Text text = m_doc.createTextNode(s);
     append(text);
  }
}
 
Example #5
Source File: DOM3TreeWalker.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks if an Text node is well-formed, by checking if it contains invalid
 * XML characters.
 *
 * @param data The contents of the comment node
 */
protected void isTextWellFormed(Text node) {
    // Does the data valid XML character data
    Character invalidChar = isWFXMLChar(node.getData());
    if (invalidChar != null) {
        String msg =
            Utils.messages.createMessage(
                MsgKey.ER_WF_INVALID_CHARACTER_IN_TEXT,
                new Object[] { Integer.toHexString(Character.getNumericValue(invalidChar.charValue())) });

        if (fErrorHandler != null) {
            fErrorHandler.handleError(
                new DOMErrorImpl(
                    DOMError.SEVERITY_FATAL_ERROR,
                    msg,
                    MsgKey.ER_WF_INVALID_CHARACTER,
                    null,
                    null,
                    null));
        }
    }
}
 
Example #6
Source File: AnnotatedPhraseCollector.java    From ttt with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void collectBaseContainer(Element e) {
    for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n instanceof Text) {
            // ignore #PCDATA
        } else if (n instanceof Element) {
            Element c = (Element) n;
            if (Documents.isElement(c, ttSpanElementName)) {
                Annotation annotation = styleCollector.getAnnotation(c);
                if (annotation == null) {
                    // ignore span children that do not specify tts:ruby
                } else if (annotation == Annotation.BASE) {
                    collectBase(c);
                } else {
                    // ignore non-base annotation children
                }
            } else {
                // ignore non-span children
            }
        }
    }
}
 
Example #7
Source File: XMLSignature.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Base64 encodes and sets the bytes as the content of the SignatureValue
 * Node.
 *
 * @param bytes bytes to be used by SignatureValue before Base64 encoding
 */
private void setSignatureValueElement(byte[] bytes) {

    while (signatureValueElement.hasChildNodes()) {
        signatureValueElement.removeChild(signatureValueElement.getFirstChild());
    }

    String base64codedValue = Base64.encode(bytes);

    if (base64codedValue.length() > 76 && !XMLUtils.ignoreLineBreaks()) {
        base64codedValue = "\n" + base64codedValue + "\n";
    }

    Text t = this.doc.createTextNode(base64codedValue);
    signatureValueElement.appendChild(t);
}
 
Example #8
Source File: WebArchiveReader.java    From coolreader with MIT License 6 votes vote down vote up
private byte[] getElBytes(Element el, String childName) {
	try {
		Node kid = el.getFirstChild();
		while (kid != null) {
			if (childName.equals(kid.getNodeName())) {
				Node nn = kid.getFirstChild();
				if (nn instanceof Text) {
					String dt = ((Text) nn).getData();
					return Base64.decode(dt, Base64.DEFAULT);
				}
			}
			kid = kid.getNextSibling();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #9
Source File: IntegrityHmac.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method engineAddContextToElement
 *
 * @param element
 */
public void engineAddContextToElement(Element element) {
    if (element == null) {
        throw new IllegalArgumentException("null element");
    }

    if (this.HMACOutputLengthSet) {
        Document doc = element.getOwnerDocument();
        Element HMElem =
            XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_HMACOUTPUTLENGTH);
        Text HMText =
            doc.createTextNode(Integer.valueOf(this.HMACOutputLength).toString());

        HMElem.appendChild(HMText);
        XMLUtils.addReturnToElement(element);
        element.appendChild(HMElem);
        XMLUtils.addReturnToElement(element);
    }
}
 
Example #10
Source File: JSONNormalizedNodeStreamWriter.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private void writeXmlValue(final Node node) throws IOException {
    Text firstChild = getFirstChildText(node);
    String childNodeText = firstChild != null ? firstChild.getWholeText() : "";
    childNodeText = childNodeText != null ? childNodeText.trim() : "";

    if (NUMBER_PATTERN.matcher(childNodeText).matches()) {
        writer.value(parseNumber(childNodeText));
        return;
    }
    switch (childNodeText) {
        case "null":
            writer.nullValue();
            break;
        case "false":
            writer.value(false);
            break;
        case "true":
            writer.value(true);
            break;
        default:
            writer.value(childNodeText);
    }
}
 
Example #11
Source File: IntegrityHmac.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method engineGetContextFromElement
 *
 * @param element
 */
protected void engineGetContextFromElement(Element element) {
    super.engineGetContextFromElement(element);

    if (element == null) {
        throw new IllegalArgumentException("element null");
    }

    Text hmaclength =
        XMLUtils.selectDsNodeText(element.getFirstChild(), Constants._TAG_HMACOUTPUTLENGTH, 0);

    if (hmaclength != null) {
        this.HMACOutputLength = Integer.parseInt(hmaclength.getData());
        this.HMACOutputLengthSet = true;
    }
}
 
Example #12
Source File: XMLDoc.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Recursively remove text nodes containing white spaces
 */
private void removeWhistespacesTextNodes(Node node) {
    if (null == node) {
        return;
    }

    NodeList list = node.getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {
        Node child = list.item(i);
        if (Node.TEXT_NODE == child.getNodeType()) {
            Text text = (Text) child;

            // if(text.isElementContentWhitespace())
            {
                node.removeChild(child);
                i--;
            }
        } else if (Node.ELEMENT_NODE == child.getNodeType()) {
            removeWhistespacesTextNodes(child);
        }
    }
}
 
Example #13
Source File: InsertToolContextClasspathTask.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
    * Update the param-value node of the context-param entry. Don't add it if it already exists.
    * 
    * @param doc
    * @param children
    * @param childNode
    */
   @Override
   protected void updateParamValue(Document doc, Node contextParamElement) {
NodeList valueChildren = contextParamElement.getChildNodes();
boolean foundEntry = false;
for (int i = 0; i < valueChildren.getLength() && !foundEntry; i++) {
    Node valueChild = valueChildren.item(i);
    if (valueChild instanceof Text) {
	String value = valueChild.getNodeValue();
	int index = value.indexOf(applicationContextPath);
	if (index >= 0) {
	    System.out.println("Application context entry " + getApplicationContextPathWithClasspath()
		    + " already in document.");
	    foundEntry = true;
	}
    }
}

if (!foundEntry) {
    System.out.println("Adding " + getApplicationContextPathWithClasspath() + " to context");
    contextParamElement.appendChild(doc.createTextNode(" " + getApplicationContextPathWithClasspath() + "\n"));
}
   }
 
Example #14
Source File: Util.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static Element nextElement(Iterator iter) {
    while (iter.hasNext()) {
        Node n = (Node) iter.next();
        if (n instanceof Text) {
            Text t = (Text) n;
            if (t.getData().trim().length() == 0)
                continue;
            fail("parsing.nonWhitespaceTextFound", t.getData().trim());
        }
        if (n instanceof Comment)
            continue;
        if (!(n instanceof Element))
            fail("parsing.elementExpected");
        return (Element) n;
    }

    return null;
}
 
Example #15
Source File: DOMBuilder.java    From anthelion with Apache License 2.0 6 votes vote down vote up
/**
 * Receive notification of character data.
 *
 * <p>The Parser will call this method to report each chunk of
 * character data.  SAX parsers may return all contiguous character
 * data in a single chunk, or they may split it into several
 * chunks; however, all of the characters in any single event
 * must come from the same external entity, so that the Locator
 * provides useful information.</p>
 *
 * <p>The application must not attempt to read from the array
 * outside of the specified range.</p>
 *
 * <p>Note that some parsers will report whitespace using the
 * ignorableWhitespace() method rather than this one (validating
 * parsers must do so).</p>
 *
 * @param ch The characters from the XML document.
 * @param start The start position in the array.
 * @param length The number of characters to read from the array.
 * @see #ignorableWhitespace
 * @see org.xml.sax.Locator
 */
public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
{
  if(isOutsideDocElem()
     && XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
    return;  // avoid DOM006 Hierarchy request error

  if (m_inCData)
  {
    cdata(ch, start, length);

    return;
  }

  String s = new String(ch, start, length);
  Node childNode;
  childNode =  m_currentNode != null ? m_currentNode.getLastChild(): null;
  if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
     ((Text)childNode).appendData(s);
  }
  else{
     Text text = m_doc.createTextNode(s);
     append(text);
  }
}
 
Example #16
Source File: XmlUtils.java    From iaf with Apache License 2.0 6 votes vote down vote up
static public String getStringValue(Element el, boolean trimWhitespace) {
	StringBuilder sb = new StringBuilder(1024);
	String str;

	NodeList nl = el.getChildNodes();
	for (int i = 0; i < nl.getLength(); ++i) {
		Node n = nl.item(i);
		if (n instanceof Text) {
			sb.append(n.getNodeValue());
		}
	}
	if (trimWhitespace) {
		str = sb.toString().trim();
	} else {
		str = sb.toString();
	}
	return str;

}
 
Example #17
Source File: XMLUtils.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Method getStrFromNode
 *
 * @param xpathnode
 * @return the string for the node.
 */
public static String getStrFromNode(Node xpathnode) {
    if (xpathnode.getNodeType() == Node.TEXT_NODE) {
        // we iterate over all siblings of the context node because eventually,
        // the text is "polluted" with pi's or comments
        StringBuilder sb = new StringBuilder();

        for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
            currentSibling != null;
            currentSibling = currentSibling.getNextSibling()) {
            if (currentSibling.getNodeType() == Node.TEXT_NODE) {
                sb.append(((Text) currentSibling).getData());
            }
        }

        return sb.toString();
    } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
        return ((Attr) xpathnode).getNodeValue();
    } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return ((ProcessingInstruction) xpathnode).getNodeValue();
    }

    return null;
}
 
Example #18
Source File: XPathContainer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the TEXT value of the <CODE>ds:XPath</CODE> Element.
 *
 * @param xpath
 */
public void setXPath(String xpath) {
    if (this.constructionElement.getChildNodes() != null) {
        NodeList nl = this.constructionElement.getChildNodes();

        for (int i = 0; i < nl.getLength(); i++) {
            this.constructionElement.removeChild(nl.item(i));
        }
    }

    Text xpathText = this.doc.createTextNode(xpath);
    this.constructionElement.appendChild(xpathText);
}
 
Example #19
Source File: TreeWalker.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Optimized dispatch of characters.
 */
private final void dispatachChars(Node node)
   throws org.xml.sax.SAXException
{
  if(m_Serializer != null)
  {
    this.m_Serializer.characters(node);
  }
  else
  {
    String data = ((Text) node).getData();
    this.m_contentHandler.characters(data.toCharArray(), 0, data.length());
  }
}
 
Example #20
Source File: TransformBase64Decode.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
void traverseElement(org.w3c.dom.Element node, StringBuilder sb) {
    Node sibling = node.getFirstChild();
    while (sibling != null) {
        switch (sibling.getNodeType()) {
        case Node.ELEMENT_NODE:
            traverseElement((Element)sibling, sb);
            break;
        case Node.TEXT_NODE:
            sb.append(((Text)sibling).getData());
        }
        sibling = sibling.getNextSibling();
    }
}
 
Example #21
Source File: DOMDocumentParser.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void appendOrCreateTextData(String textData) {
    Node lastChild = _currentNode.getLastChild();
    if (lastChild instanceof Text) {
        ((Text) lastChild).appendData(textData);
    } else {
        _currentNode.appendChild(
                _document.createTextNode(textData));
    }
}
 
Example #22
Source File: XMLUtils.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method getFullTextChildrenFromElement
 *
 * @param element
 * @return the string of children
 */
public static String getFullTextChildrenFromElement(Element element) {
    StringBuilder sb = new StringBuilder();

    Node child = element.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.TEXT_NODE) {
            sb.append(((Text)child).getData());
        }
        child = child.getNextSibling();
    }

    return sb.toString();
}
 
Example #23
Source File: ElementProxy.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Method addText
 *
 * @param text
 */
public void addText(String text) {
    if (text != null) {
        Text t = this.doc.createTextNode(text);

        this.constructionElement.appendChild(t);
    }
}
 
Example #24
Source File: ExtensionUtils.java    From hybris-commerce-eclipse-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Adds extension to the local extension
 * 
 * @param source
 *            source directory
 * @param extensionName
 *            name of extension
 * 
 * @throws TransformerException
 */
public static void addToLocalExtension(File source, String workingSetName, String extensionName)
		throws SAXException, IOException, ParserConfigurationException, TransformerException {
	File xmlFile = new File(PathUtils.getLocalExtensionsPath());
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(xmlFile);
	doc.getDocumentElement().normalize();

	Node extensions = doc.getElementsByTagName("extensions").item(0);
	Attr dirAttr = doc.createAttribute("dir");
	dirAttr.setValue(source + File.separator + extensionName);
	Element extension = doc.createElement("extension");
	extension.setAttributeNode(dirAttr);
	if (!workingSetName.isEmpty()) {
		if (getWorkingSets().contains(workingSetName)) {
			extensions.insertBefore(extension, getFirstExtensionNodeFromWorkingSet(extensions, workingSetName));
		} else {
			Comment workingSet = doc.createComment(workingSetName);
			Text newLine = doc.createTextNode(" \n");
			extensions.appendChild(workingSet);
			extensions.appendChild(newLine);
			extensions.appendChild(extension);
		}
	} else {
		extensions.insertBefore(extension, getFirstExtensionNode(extensions));
	}
	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
	DOMSource domSource = new DOMSource(doc);
	StreamResult result = new StreamResult(xmlFile);
	transformer.transform(domSource, result);
}
 
Example #25
Source File: XMLUtils.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Method getFullTextChildrenFromElement
 *
 * @param element
 * @return the string of children
 */
public static String getFullTextChildrenFromElement(Element element) {
    StringBuilder sb = new StringBuilder();

    Node child = element.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.TEXT_NODE) {
            sb.append(((Text)child).getData());
        }
        child = child.getNextSibling();
    }

    return sb.toString();
}
 
Example #26
Source File: DOMPrinter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void print(Node node) throws XMLStreamException {
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        visitDocument((Document) node);
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        visitDocumentFragment((DocumentFragment) node);
        break;
    case Node.ELEMENT_NODE:
        visitElement((Element) node);
        break;
    case Node.TEXT_NODE:
        visitText((Text) node);
        break;
    case Node.CDATA_SECTION_NODE:
        visitCDATASection((CDATASection) node);
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        visitProcessingInstruction((ProcessingInstruction) node);
        break;
    case Node.ENTITY_REFERENCE_NODE:
        visitReference((EntityReference) node);
        break;
    case Node.COMMENT_NODE:
        visitComment((Comment) node);
        break;
    case Node.DOCUMENT_TYPE_NODE:
        break;
    case Node.ATTRIBUTE_NODE:
    case Node.ENTITY_NODE:
    default:
        throw new XMLStreamException("Unexpected DOM Node Type "
            + node.getNodeType()
        );
    }
}
 
Example #27
Source File: DOMDifferenceEngineTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test public void textAndCDataMatchRecursively() {
    Element e1 = doc.createElement("foo");
    Element e2 = doc.createElement("foo");
    Text fooText = doc.createTextNode("foo");
    e1.appendChild(fooText);
    CDATASection fooCDATASection = doc.createCDATASection("foo");
    e2.appendChild(fooCDATASection);
    DOMDifferenceEngine d = new DOMDifferenceEngine();
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(e1, new XPathContext(),
                                e2, new XPathContext()));
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(e2, new XPathContext(),
                                e1, new XPathContext()));
}
 
Example #28
Source File: UnImplNode.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Unimplemented. See org.w3c.dom.Document
 *
 * @param data Data for text node
 *
 * @return null
 */
public Text createTextNode(String data)
{

  error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED);

  return null;
}
 
Example #29
Source File: NippinOptionalDeflateTransformer.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private void traverseElement(Element node, StringBuilder sb) {
   for(Node sibling = node.getFirstChild(); sibling != null; sibling = sibling.getNextSibling()) {
      switch(sibling.getNodeType()) {
      case 1:
         this.traverseElement((Element)sibling, sb);
         break;
      case 3:
         sb.append(((Text)sibling).getData());
      }
   }

}
 
Example #30
Source File: AbstractHtmlParseFilter.java    From nutch-htmlunit with Apache License 2.0 5 votes vote down vote up
protected String getXPathValue(Node contextNode, String xpath, String defaultVal) {
    Node node = selectSingleNode(contextNode, xpath);
    if (node == null) {
        return defaultVal;
    } else {
        String txt = null;
        if (node instanceof Text) {
            txt = node.getNodeValue();
        } else {
            txt = node.getTextContent();
        }
        return cleanInvisibleChar(txt);
    }
}