Java Code Examples for org.w3c.dom.Document#createTextNode()
The following examples show how to use
org.w3c.dom.Document#createTextNode() .
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: SvgRenderer.java From OkapiBarcode with Apache License 2.0 | 6 votes |
/** * Cleans / sanitizes the specified string for inclusion in XML. A bit convoluted, but we're * trying to do it without adding an external dependency just for this... * * @param s the string to be cleaned / sanitized * @return the cleaned / sanitized string */ protected String clean(String s) { // remove control characters s = s.replaceAll("[\u0000-\u001f]", ""); // escape XML characters try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Text text = document.createTextNode(s); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(text); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(source, result); return writer.toString(); } catch (ParserConfigurationException | TransformerException | TransformerFactoryConfigurationError e) { return s; } }
Example 2
Source File: XStreamMarshallerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void marshalDOMResult() throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); Document document = builder.newDocument(); DOMResult domResult = new DOMResult(document); marshaller.marshal(flight, domResult); Document expected = builder.newDocument(); Element flightElement = expected.createElement("flight"); expected.appendChild(flightElement); Element numberElement = expected.createElement("flightNumber"); flightElement.appendChild(numberElement); Text text = expected.createTextNode("42"); numberElement.appendChild(text); assertXMLEqual("Marshaller writes invalid DOMResult", expected, document); }
Example 3
Source File: IssueSamlUnitTest.java From cxf with Apache License 2.0 | 6 votes |
private UseKeyType createUseKey(Crypto crypto, String alias) throws Exception { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(alias); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); Document doc = DOMUtils.getEmptyDocument(); Element x509Data = doc.createElementNS(WSS4JConstants.SIG_NS, "ds:X509Data"); x509Data.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:ds", WSS4JConstants.SIG_NS); Element x509Cert = doc.createElementNS(WSS4JConstants.SIG_NS, "ds:X509Certificate"); Text certText = doc.createTextNode(Base64.getMimeEncoder().encodeToString(certs[0].getEncoded())); x509Cert.appendChild(certText); x509Data.appendChild(x509Cert); UseKeyType useKey = new UseKeyType(); useKey.setAny(x509Data); return useKey; }
Example 4
Source File: IntegrityHmac.java From jdk1.8-source-analysis with Apache License 2.0 | 6 votes |
/** * 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 5
Source File: IntegrityHmac.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * 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 6
Source File: AbstractManifestBuilder.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
protected Element addDataObjectReference(final Document documentDom, final Element asicManifestDom, DSSDocument document, DigestAlgorithm digestAlgorithm) { final Element dataObjectReferenceDom = DomUtils.addElement(documentDom, asicManifestDom, ASiCNamespace.NS, ASiCElement.DATA_OBJECT_REFERENCE); final String name = document.getName() != null ? document.getName() : ASiCUtils.ZIP_ENTRY_DETACHED_FILE; dataObjectReferenceDom.setAttribute(ASiCAttribute.URI.getAttributeName(), DSSUtils.encodeURI(name)); MimeType mimeType = document.getMimeType(); if (mimeType != null) { dataObjectReferenceDom.setAttribute(ASiCAttribute.MIME_TYPE.getAttributeName(), mimeType.getMimeTypeString()); } final Element digestMethodDom = DomUtils.addElement(documentDom, dataObjectReferenceDom, XMLDSigNamespace.NS, XMLDSigElement.DIGEST_METHOD); digestMethodDom.setAttribute(XMLDSigAttribute.ALGORITHM.getAttributeName(), digestAlgorithm.getUri()); final Element digestValueDom = DomUtils.addElement(documentDom, dataObjectReferenceDom, XMLDSigNamespace.NS, XMLDSigElement.DIGEST_VALUE); final Text textNode = documentDom.createTextNode(document.getDigest(digestAlgorithm)); digestValueDom.appendChild(textNode); return dataObjectReferenceDom; }
Example 7
Source File: DOMConfigurationTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Equivalence class partitioning with state and input values orientation * for public void setParameter(String name, Object value) throws * DOMException, <br> * <b>pre-conditions</b>: the document root element has a text node with * four white space characters, <br> * <b>name</b>: element-content-whitespace <br> * <b>value</b>: false. <br> * <b>Expected results</b>: the text node is discarded */ @Test public void testECWhitespace002() { Document doc = null; try { doc = loadDocument(null, test3_xml); } catch (Exception e) { Assert.fail(e.getMessage()); } Element root = doc.getDocumentElement(); Text text = doc.createTextNode("\t\n\r "); root.appendChild(text); DOMConfiguration config = doc.getDomConfig(); if (!config.canSetParameter("element-content-whitespace", Boolean.FALSE)) { System.out.println("OK, setting 'element-content-whitespace' to false is not supported"); return; } config.setParameter("element-content-whitespace", Boolean.FALSE); if (!config.canSetParameter("validate", Boolean.TRUE)) { System.out.println("OK, setting 'validate' to true is not supported"); return; } config.setParameter("validate", Boolean.TRUE); setHandler(doc); doc.normalizeDocument(); Node firstChild = root.getFirstChild(); if (firstChild != null) { Assert.fail("the first child is " + firstChild + ", but no child is expected"); } return; // Status.passed("OK"); }
Example 8
Source File: ExsltStrings.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * The str:split function splits up a string and returns a node set of token * elements, each containing one token from the string. * <p> * The first argument is the string to be split. The second argument is a pattern * string. The string given by the first argument is split at any occurrence of * this pattern. For example: * <pre> * str:split('a, simple, list', ', ') gives the node set consisting of: * * <token>a</token> * <token>simple</token> * <token>list</token> * </pre> * If the second argument is omitted, the default is the string ' ' (i.e. a space). * * @param str The string to be split * @param pattern The pattern * * @return A node set of split tokens */ public static NodeList split(String str, String pattern) { NodeSet resultSet = new NodeSet(); resultSet.setShouldCacheNodes(true); boolean done = false; int fromIndex = 0; int matchIndex = 0; String token = null; while (!done && fromIndex < str.length()) { matchIndex = str.indexOf(pattern, fromIndex); if (matchIndex >= 0) { token = str.substring(fromIndex, matchIndex); fromIndex = matchIndex + pattern.length(); } else { done = true; token = str.substring(fromIndex); } Document doc = getDocument(); synchronized (doc) { Element element = doc.createElement("token"); Text text = doc.createTextNode(token); element.appendChild(text); resultSet.addNode(element); } } return resultSet; }
Example 9
Source File: XAdESExtensionFromLTToLTAWithIndentsTest.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
private DSSDocument addCustomIndents(DSSDocument document) { Document documentDom = DomUtils.buildDOM(document); Node unsignedSignaturePropertiesNode = DomUtils.getNode(documentDom, AbstractPaths.all(XAdES132Element.UNSIGNED_SIGNATURE_PROPERTIES)); Text customIndents = documentDom.createTextNode("\n\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\n\n\n\n"); Node firstChild = getFirstElement(unsignedSignaturePropertiesNode); unsignedSignaturePropertiesNode.insertBefore(customIndents, firstChild); Text customIndentsClone = documentDom.createTextNode("\n\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\n\n\n\n"); firstChild.insertBefore(customIndentsClone, getFirstElement(firstChild)); return DomUtils.createDssDocumentFromDomDocument(documentDom, "signedDocWithIndents"); }
Example 10
Source File: XMLHelper.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Creates a text node with the given content and appends it as child to the given element. * * @param domElement the element to recieve the text node * @param textContent the content for the text node */ public static void appendTextContent(Element domElement, String textContent) { if (textContent == null) { return; } Document parentDocument = domElement.getOwnerDocument(); Text textNode = parentDocument.createTextNode(textContent); domElement.appendChild(textNode); }
Example 11
Source File: Phoneme.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
/** * Create a new text within this block. * @param text The text to be added. * @return The new created text. */ public Text addText(final String text) { final Document document = getOwnerDocument(); final Node node = document.createTextNode(text); final Text textNode = new Text(node, getNodeFactory()); appendChild(textNode); return textNode; }
Example 12
Source File: DomReader.java From cosmo with Apache License 2.0 | 4 votes |
private static Node readNode(Document d, XMLStreamReader reader) throws XMLStreamException { Node root = null; Node current = null; while (reader.hasNext()) { reader.next(); if (reader.isEndElement()) { if (current.getParentNode() == null) { break; } current = current.getParentNode(); } if (reader.isStartElement()) { Element e = readElement(d, reader); if (root == null) { root = e; } if (current != null) { current.appendChild(e); } current = e; continue; } if (reader.isCharacters()) { CharacterData cd = d.createTextNode(reader.getText()); if (root == null) { return cd; } if (current == null) { return cd; } current.appendChild(cd); continue; } } return root; }
Example 13
Source File: XMLWriter.java From oopsla15-artifact with Eclipse Public License 1.0 | 4 votes |
private Node yieldString(IString value, Document doc) { return doc.createTextNode(value.getValue()); }
Example 14
Source File: ProcessorUtil.java From cxf with Apache License 2.0 | 4 votes |
public static Node cloneNode(Document document, Node node, boolean deep) throws DOMException { if (document == null || node == null) { return null; } int type = node.getNodeType(); if (node.getOwnerDocument() == document) { return node.cloneNode(deep); } Node clone; switch (type) { case Node.CDATA_SECTION_NODE: clone = document.createCDATASection(node.getNodeValue()); break; case Node.COMMENT_NODE: clone = document.createComment(node.getNodeValue()); break; case Node.ENTITY_REFERENCE_NODE: clone = document.createEntityReference(node.getNodeName()); break; case Node.ELEMENT_NODE: clone = document.createElementNS(node.getNamespaceURI(), node.getNodeName()); NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr)attributes.item(i); Attr attrnew = ((Element)clone).getOwnerDocument().createAttributeNS(attr.getNamespaceURI(), attr.getNodeName()); attrnew.setValue(attr.getNodeValue()); ((Element)clone).setAttributeNodeNS(attrnew); } break; case Node.TEXT_NODE: clone = document.createTextNode(node.getNodeValue()); break; default: return null; } if (deep && type == Node.ELEMENT_NODE) { Node child = node.getFirstChild(); while (child != null) { clone.appendChild(cloneNode(document, child, true)); child = child.getNextSibling(); } } return clone; }
Example 15
Source File: DOMUtil.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Copies the source tree into the specified place in a destination * tree. The source node and its children are appended as children * of the destination node. * <p> * <em>Note:</em> This is an iterative implementation. */ public static void copyInto(Node src, Node dest) throws DOMException { // get node factory Document factory = dest.getOwnerDocument(); boolean domimpl = factory instanceof DocumentImpl; // placement variables Node start = src; Node parent = src; Node place = src; // traverse source tree while (place != null) { // copy this node Node node = null; int type = place.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: { node = factory.createCDATASection(place.getNodeValue()); break; } case Node.COMMENT_NODE: { node = factory.createComment(place.getNodeValue()); break; } case Node.ELEMENT_NODE: { Element element = factory.createElement(place.getNodeName()); node = element; NamedNodeMap attrs = place.getAttributes(); int attrCount = attrs.getLength(); for (int i = 0; i < attrCount; i++) { Attr attr = (Attr)attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); element.setAttribute(attrName, attrValue); if (domimpl && !attr.getSpecified()) { ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false); } } break; } case Node.ENTITY_REFERENCE_NODE: { node = factory.createEntityReference(place.getNodeName()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue()); break; } case Node.TEXT_NODE: { node = factory.createTextNode(place.getNodeValue()); break; } default: { throw new IllegalArgumentException("can't copy node type, "+ type+" ("+ place.getNodeName()+')'); } } dest.appendChild(node); // iterate over children if (place.hasChildNodes()) { parent = place; place = place.getFirstChild(); dest = node; } // advance else { place = place.getNextSibling(); while (place == null && parent != start) { place = parent.getNextSibling(); parent = parent.getParentNode(); dest = dest.getParentNode(); } } } }
Example 16
Source File: Extensions.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
/** * This method is an extension that implements as a Xalan extension * the node-set function also found in xt and saxon. * If the argument is a Result Tree Fragment, then <code>nodeset</code> * returns a node-set consisting of a single root node as described in * section 11.1 of the XSLT 1.0 Recommendation. If the argument is a * node-set, <code>nodeset</code> returns a node-set. If the argument * is a string, number, or boolean, then <code>nodeset</code> returns * a node-set consisting of a single root node with a single text node * child that is the result of calling the XPath string() function on the * passed parameter. If the argument is anything else, then a node-set * is returned consisting of a single root node with a single text node * child that is the result of calling the java <code>toString()</code> * method on the passed argument. * Most of the * actual work here is done in <code>MethodResolver</code> and * <code>XRTreeFrag</code>. * @param myProcessor Context passed by the extension processor * @param rtf Argument in the stylesheet to the nodeset extension function * * NEEDSDOC ($objectName$) @return */ public static NodeSet nodeset(ExpressionContext myProcessor, Object rtf) { String textNodeValue; if (rtf instanceof NodeIterator) { return new NodeSet((NodeIterator) rtf); } else { if (rtf instanceof String) { textNodeValue = (String) rtf; } else if (rtf instanceof Boolean) { textNodeValue = new XBoolean(((Boolean) rtf).booleanValue()).str(); } else if (rtf instanceof Double) { textNodeValue = new XNumber(((Double) rtf).doubleValue()).str(); } else { textNodeValue = rtf.toString(); } // This no longer will work right since the DTM. // Document myDoc = myProcessor.getContextNode().getOwnerDocument(); Document myDoc = JdkXmlUtils.getDOMDocument(); Text textNode = myDoc.createTextNode(textNodeValue); DocumentFragment docFrag = myDoc.createDocumentFragment(); docFrag.appendChild(textNode); return new NodeSet(docFrag); } }
Example 17
Source File: XmlUtils.java From LiveQAServerDemo with MIT License | 3 votes |
/** * Creates a new element, with the given text inside that element. * * @param document the document into which the element is added. * @param parentElement The parent element of the element-to-be-added. * @param newElementName name of new element (tag-name). * @param textString the text to be written inside the newly created element. * @return The new element. */ public static Element addElementWithText(Document document, Element parentElement, String newElementName, String textString) { Element newElement = document.createElement(newElementName); Text text = document.createTextNode(textString); newElement.appendChild(text); parentElement.appendChild(newElement); return newElement; }
Example 18
Source File: Base64.java From openjdk-jdk8u with GNU General Public License v2.0 | 3 votes |
/** * Method encodeToElement * * @param doc * @param localName * @param bytes * @return an Element with the base64 encoded in the text. * */ public static final Element encodeToElement(Document doc, String localName, byte[] bytes) { Element el = XMLUtils.createElementInSignatureSpace(doc, localName); Text text = doc.createTextNode(encode(bytes)); el.appendChild(text); return el; }
Example 19
Source File: Base64.java From jdk8u_jdk with GNU General Public License v2.0 | 3 votes |
/** * Method encodeToElement * * @param doc * @param localName * @param bytes * @return an Element with the base64 encoded in the text. * */ public static final Element encodeToElement(Document doc, String localName, byte[] bytes) { Element el = XMLUtils.createElementInSignatureSpace(doc, localName); Text text = doc.createTextNode(encode(bytes)); el.appendChild(text); return el; }
Example 20
Source File: DomUtils.java From dss with GNU Lesser General Public License v2.1 | 2 votes |
/** * This method sets a text node to the given DOM element. * * @param document * root document * @param parentDom * parent node * @param text * text to be added */ public static void setTextNode(final Document document, final Element parentDom, final String text) { final Text textNode = document.createTextNode(text); parentDom.appendChild(textNode); }