org.w3c.dom.Document#createTextNode ( )源码实例Demo

下面列出了org.w3c.dom.Document#createTextNode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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);
}
 
源代码2 项目: dss   文件: AbstractManifestBuilder.java
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;
}
 
源代码3 项目: hottub   文件: IntegrityHmac.java
/**
 * 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);
    }
}
 
源代码4 项目: jdk1.8-source-analysis   文件: IntegrityHmac.java
/**
 * 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);
    }
}
 
源代码5 项目: cxf   文件: IssueSamlUnitTest.java
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;
}
 
源代码6 项目: OkapiBarcode   文件: SvgRenderer.java
/**
 * 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;
    }
}
 
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");
}
 
源代码8 项目: JVoiceXML   文件: Phoneme.java
/**
 * 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;
}
 
源代码9 项目: lams   文件: XMLHelper.java
/**
 * 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);
}
 
源代码10 项目: openjdk-jdk9   文件: DOMConfigurationTest.java
/**
 * 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");

}
 
源代码11 项目: openjdk-8-source   文件: ExsltStrings.java
/**
 * 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 '&#x20;' (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;
}
 
源代码12 项目: cxf   文件: ProcessorUtil.java
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;
}
 
源代码13 项目: oopsla15-artifact   文件: XMLWriter.java
private Node yieldString(IString value, Document doc) {
	return doc.createTextNode(value.getValue());
}
 
源代码14 项目: cosmo   文件: DomReader.java
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;
}
 
源代码15 项目: openjdk-jdk9   文件: DOMUtil.java
/**
 * 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();
            }
        }

    }

}
 
源代码16 项目: openjdk-jdk8u   文件: Extensions.java
/**
 * 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);
  }
}
 
源代码17 项目: jdk8u_jdk   文件: Base64.java
/**
 * 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;
}
 
源代码18 项目: openjdk-jdk8u   文件: Base64.java
/**
 * 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;
}
 
源代码19 项目: LiveQAServerDemo   文件: XmlUtils.java
/**
 * 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;
}
 
源代码20 项目: dss   文件: DomUtils.java
/**
 * 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);
}