Java Code Examples for org.w3c.dom.Element#appendChild()

The following examples show how to use org.w3c.dom.Element#appendChild() . 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: XMLSchemaInternalizationLogic.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new XML Schema element of the given local name
 * and insert it as the first child of the given parent node.
 *
 * @return
 *      Newly create element.
 */
private Element insertXMLSchemaElement( Element parent, String localName ) {
    // use the same prefix as the parent node to avoid modifying
    // the namespace binding.
    String qname = parent.getTagName();
    int idx = qname.indexOf(':');
    if(idx==-1)     qname = localName;
    else            qname = qname.substring(0,idx+1)+localName;

    Element child = parent.getOwnerDocument().createElementNS( WellKnownNamespace.XML_SCHEMA, qname );

    NodeList children = parent.getChildNodes();

    if( children.getLength()==0 )
        parent.appendChild(child);
    else
        parent.insertBefore( child, children.item(0) );

    return child;
}
 
Example 2
Source File: DOMKeyValue.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
                      DOMCryptoContext context)
    throws MarshalException
{
    Element dsaElem = DOMUtils.createElement(doc, "DSAKeyValue",
                                             XMLSignature.XMLNS,
                                             dsPrefix);
    // parameters J, Seed & PgenCounter are not included
    Element pElem = DOMUtils.createElement(doc, "P", XMLSignature.XMLNS,
                                           dsPrefix);
    Element qElem = DOMUtils.createElement(doc, "Q", XMLSignature.XMLNS,
                                           dsPrefix);
    Element gElem = DOMUtils.createElement(doc, "G", XMLSignature.XMLNS,
                                           dsPrefix);
    Element yElem = DOMUtils.createElement(doc, "Y", XMLSignature.XMLNS,
                                           dsPrefix);
    p.marshal(pElem, dsPrefix, context);
    q.marshal(qElem, dsPrefix, context);
    g.marshal(gElem, dsPrefix, context);
    y.marshal(yElem, dsPrefix, context);
    dsaElem.appendChild(pElem);
    dsaElem.appendChild(qElem);
    dsaElem.appendChild(gElem);
    dsaElem.appendChild(yElem);
    parent.appendChild(dsaElem);
}
 
Example 3
Source File: XMLUtils.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private static void extractAttributesToElements(Element root) {
    NamedNodeMap attributeMap = root.getAttributes();
    for (int i = 0; i < attributeMap.getLength(); i++) {
        Attr attr = (Attr) attributeMap.item(i);
        if (isNamespaceDef(attr)) {
            continue;
        }

        Element attrElement = root.getOwnerDocument().createElement(attr.getName());
        attrElement.setTextContent(attr.getValue());
        root.appendChild(attrElement);
    }

    NodeList children = root.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i) instanceof Element) {
            extractAttributesToElements((Element) children.item(i));
        }
    }
}
 
Example 4
Source File: DOMDifferenceEngineTest.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@Test public void compareNodesDifferentNumberOfChildren() {
    DOMDifferenceEngine d = new DOMDifferenceEngine();
    DiffExpecter ex =
        new DiffExpecter(ComparisonType.CHILD_NODELIST_LENGTH, 2);
    d.addDifferenceListener(ex);
    d.setComparisonController(ComparisonControllers.StopWhenDifferent);
    Element e1 = doc.createElement("x");
    Element e2 = doc.createElement("x");
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(e1, new XPathContext(),
                                e2, new XPathContext()));
    e1.appendChild(doc.createElement("x"));
    assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
                 d.compareNodes(e1, new XPathContext(),
                                e2, new XPathContext()));
    assertEquals(1, ex.invoked);
    e2.appendChild(doc.createElement("x"));
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(e1, new XPathContext(),
                                e2, new XPathContext()));
    e2.appendChild(doc.createElement("x"));
    assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
                 d.compareNodes(e1, new XPathContext(),
                                e2, new XPathContext()));
    assertEquals(2, ex.invoked);
}
 
Example 5
Source File: AjaxSpiderAPI.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public void toXML(Document doc, Element parent) {
    parent.setAttribute("type", "set");

    Element el = doc.createElement(inScope.getName());
    inScope.toXML(doc, el);
    parent.appendChild(el);

    el = doc.createElement(outOfScope.getName());
    outOfScope.toXML(doc, el);
    parent.appendChild(el);

    el = doc.createElement(errors.getName());
    errors.toXML(doc, el);
    parent.appendChild(el);
}
 
Example 6
Source File: HeritrixRegexpParameterValueModifier.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addRegexpAsParameter(String regexp, Node node, Document document, String url) {
    if (StringUtils.isBlank(regexp)) {
        return;
    }
    String builtRegexp;
    builtRegexp = buildRegexp(regexp, url);
    Logger.getLogger(HeritrixParameterValueModifier.class.getName()).debug(" builtRegexp " + builtRegexp);
    if (StringUtils.isNotBlank(builtRegexp) && compileRegexp(regexp)) {
        Element element = document.createElement(getElementName());
        element.appendChild(document.createTextNode(builtRegexp));
        node.appendChild(element);
    }
}
 
Example 7
Source File: ElementProxy.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method addTextElement
 *
 * @param text
 * @param localname
 */
public void addTextElement(String text, String localname) {
    Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname);
    Text t = this.doc.createTextNode(text);

    e.appendChild(t);
    this.constructionElement.appendChild(e);
    XMLUtils.addReturnToElement(this.constructionElement);
}
 
Example 8
Source File: IssueSamlUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Element createAppliesToURIElement(String addressUrl) {
    Document doc = DOMUtils.getEmptyDocument();
    Element appliesTo = doc.createElementNS(STSConstants.WSP_NS, "wsp:AppliesTo");
    appliesTo.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:wsp", STSConstants.WSP_NS);

    Element uri = doc.createElementNS(STSConstants.WSP_NS, "wsp:URI");
    uri.setTextContent(addressUrl);
    appliesTo.appendChild(uri);

    return appliesTo;
}
 
Example 9
Source File: DOMX509Data.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void marshalSKI(byte[] skid, Node parent, Document doc,
                        String dsPrefix)
{
    Element skidElem = DOMUtils.createElement(doc, "X509SKI",
                                              XMLSignature.XMLNS, dsPrefix);
    skidElem.appendChild(doc.createTextNode(Base64.encode(skid)));
    parent.appendChild(skidElem);
}
 
Example 10
Source File: MapLayout.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void exportLayout(Document m_Doc, Element parent) {
    Element layout = m_Doc.createElement("Layout");

    //Add attribute
    Attr BackColor = m_Doc.createAttribute("BackColor");
    Attr ForeColor = m_Doc.createAttribute("ForeColor");
    Attr SmoothingMode = m_Doc.createAttribute("SmoothingMode");
    Attr PaperSizeName = m_Doc.createAttribute("PaperSizeName");
    Attr PaperSizeWidth = m_Doc.createAttribute("PaperSizeWidth");
    Attr PaperSizeHeight = m_Doc.createAttribute("PaperSizeHeight");
    Attr Landscape = m_Doc.createAttribute("Landscape");

    BackColor.setValue(ColorUtil.toHexEncoding(_pageBackColor));
    ForeColor.setValue(ColorUtil.toHexEncoding(_pageForeColor));
    SmoothingMode.setValue(String.valueOf(_antiAlias));
    PaperSizeName.setValue(_paperSize.getName());
    PaperSizeWidth.setValue(String.valueOf(_paperSize.getWidth()));
    PaperSizeHeight.setValue(String.valueOf(_paperSize.getHeight()));
    Landscape.setValue(String.valueOf(_isLandscape));

    layout.setAttributeNode(BackColor);
    layout.setAttributeNode(ForeColor);
    layout.setAttributeNode(SmoothingMode);
    layout.setAttributeNode(PaperSizeName);
    layout.setAttributeNode(PaperSizeWidth);
    layout.setAttributeNode(PaperSizeHeight);
    layout.setAttributeNode(Landscape);

    parent.appendChild(layout);

    //Add layout elements
    addLayoutElements(m_Doc, layout);
}
 
Example 11
Source File: DOMRetrievalMethod.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);
    Element rmElem = DOMUtils.createElement(ownerDoc, "RetrievalMethod",
                                            XMLSignature.XMLNS, dsPrefix);

    // add URI and Type attributes
    DOMUtils.setAttribute(rmElem, "URI", uri);
    DOMUtils.setAttribute(rmElem, "Type", type);

    // add Transforms elements
    if (!transforms.isEmpty()) {
        Element transformsElem = DOMUtils.createElement(ownerDoc,
                                                        "Transforms",
                                                        XMLSignature.XMLNS,
                                                        dsPrefix);
        rmElem.appendChild(transformsElem);
        for (Transform transform : transforms) {
            ((DOMTransform)transform).marshal(transformsElem,
                                               dsPrefix, context);
        }
    }

    parent.appendChild(rmElem);

    // save here node
    here = rmElem.getAttributeNodeNS(null, "URI");
}
 
Example 12
Source File: RoleClaimsCallbackHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Claims Element for a "role"
 */
private Element createClaims() {
    Document doc = DOMUtils.getEmptyDocument();
    Element claimsElement =
        doc.createElementNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "Claims");
    claimsElement.setAttributeNS(null, "Dialect", "http://schemas.xmlsoap.org/ws/2005/05/identity");
    Element claimType =
        doc.createElementNS("http://schemas.xmlsoap.org/ws/2005/05/identity", "ClaimType");
    claimType.setAttributeNS(null, "Uri", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
    claimsElement.appendChild(claimType);
    return claimsElement;
}
 
Example 13
Source File: ExsltStrings.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: ServiceBuilder.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Build arguments tags
 *
 * <argument type="service" id="foobar"/>
 */
private void appendArgumentXmlTags(@NotNull Document doc, @NotNull Element rootElement, @NotNull List<String> parameters) {
    for(String parameter: parameters) {
        Element argument = doc.createElement("argument");
        argument.setAttribute("type", "service");
        argument.setAttribute("id", parameter);
        rootElement.appendChild(argument);
    }
}
 
Example 15
Source File: DOMX509Data.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private void marshalSubjectName(String name, Node parent, Document doc,
                                String dsPrefix)
{
    Element snElem = DOMUtils.createElement(doc, "X509SubjectName",
                                            XMLSignature.XMLNS, dsPrefix);
    snElem.appendChild(doc.createTextNode(name));
    parent.appendChild(snElem);
}
 
Example 16
Source File: QueryXmlHelper.java    From pentaho-metadata with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void addParametersToDocument( Document doc, Element parametersElement, Query query ) {
  for ( Parameter param : query.getParameters() ) {
    Element paramElement = doc.createElement( "parameter" ); //$NON-NLS-1$
    paramElement.setAttribute( "name", param.getName() ); //$NON-NLS-1$
    paramElement.setAttribute( "type", param.getType().toString() ); //$NON-NLS-1$
    paramElement.setAttribute(
        "defaultValue", param.getDefaultValue() == null ? "" : param.getDefaultValue().toString() ); //$NON-NLS-1$ //$NON-NLS-2$
    parametersElement.appendChild( paramElement );
  }
}
 
Example 17
Source File: LiteralImpl.java    From jason with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** get as XML */
@Override
public Element getAsDOM(Document document) {
    Element u = (Element) document.createElement("literal");
    u.setAttribute("namespace", getNS().getFunctor());
    if (negated()) {
        u.setAttribute("negated", negated()+"");
    }
    u.appendChild(super.getAsDOM(document));
    return u;
}
 
Example 18
Source File: ItemHelper12Impl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private void addEMIItem(String ident, ItemTextIfc itemText, Item itemXml) {
	//main node resprocessing
	Element resprocessing = createElement("resprocessing", itemXml);
	itemXml.addElement("item", resprocessing);
	//outcomes with the scores and required count
	Element outcomes = createElement("outcomes", itemXml);
	resprocessing.appendChild(outcomes);
	//decvar for score
	Element decvarScore = createElement("decvar", itemXml);
	decvarScore.setAttribute("defaultval", "0");
	decvarScore.setAttribute("varname", "SCORE");
	decvarScore.setAttribute("vartype", "Double");
	outcomes.appendChild(decvarScore);
	//decvar for required count
	Element decvarRequired = createElement("decvar", itemXml);
	decvarRequired.setAttribute("defaultval", String.valueOf(itemText.getEmiCorrectOptionLabels().length()));
	decvarRequired.setAttribute("maxvalue", itemText.getRequiredOptionsCount().toString());
	decvarRequired.setAttribute("minvalue", "0");
	decvarRequired.setAttribute("varname", "requiredOptionsCount");
	decvarRequired.setAttribute("vartype", "Integer");
	outcomes.appendChild(decvarRequired);
	//decvar for score user set
	Element decvarScoreUserSet = createElement("decvar", itemXml);
	decvarScoreUserSet.setAttribute("varname", "scoreUserSet");
	decvarScoreUserSet.setAttribute("vartype", "String");
	outcomes.appendChild(decvarScoreUserSet);
	//Item Text
	Element interpretvar = createElement("interpretvar", itemXml);//Testing
	outcomes.appendChild(interpretvar);//Testing
	Element material = createElement("material", itemXml);//Testing
	interpretvar.appendChild(material);//Testing
	Element mattext = createElement("mattext", itemXml);//Testing
	mattext.setTextContent(XmlUtil.convertToSingleCDATA(itemText.getText()));//Testing
	material.appendChild(mattext);//Testing
	if(itemText.getHasAttachment()){
		setAttachments(itemText.getItemTextAttachmentSet(), itemXml, material);
	}
	
	double score = 0.0;
	double discount = 0.0;
	//respcondition for every correct option
	for(AnswerIfc answer: itemText.getAnswerArraySorted()){
		decvarScoreUserSet.setAttribute("defaultval", answer.getGrade());
		Element respcondition = createElement("respcondition", itemXml);
		respcondition.setAttribute("continue", "Yes");
		respcondition.setAttribute("title", answer.getIsCorrect()?"CORRECT":"INCORRECT");
		resprocessing.appendChild(respcondition);
		//conditionvar for correct answers
		Element conditionvar = createElement("conditionvar", itemXml);
		respcondition.appendChild(conditionvar);
		Element varequal = createElement("varequal", itemXml);
		varequal.setAttribute("case", "Yes");
		varequal.setAttribute("respident", ident);
		varequal.setTextContent(answer.getLabel());
		conditionvar.appendChild(varequal);
		//setvar for action
		Element setvar = createElement("setvar", itemXml);
		if(answer.getIsCorrect()){
			setvar.setAttribute("action", "Add");
			setvar.setTextContent(String.valueOf(getDouble(answer.getScore())));
			score += getDouble(answer.getScore());
		}else{
			setvar.setAttribute("action", "Subtract");
			setvar.setTextContent(String.valueOf(Math.abs(getDouble(answer.getDiscount()))));
			discount += getDouble(answer.getDiscount());
		}
		setvar.setAttribute("varname", "SCORE");
		respcondition.appendChild(setvar);
	}
	
	//set the scores
	decvarScore.setAttribute("maxvalue", String.valueOf(getDouble(score)));
	decvarScore.setAttribute("minvalue", "0");//String.valueOf(getDouble(discount)));
}
 
Example 19
Source File: DOMReference.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Marshalling Reference");
    }
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    refElem = DOMUtils.createElement(ownerDoc, "Reference",
                                     XMLSignature.XMLNS, dsPrefix);

    // set attributes
    DOMUtils.setAttributeID(refElem, "Id", id);
    DOMUtils.setAttribute(refElem, "URI", uri);
    DOMUtils.setAttribute(refElem, "Type", type);

    // create and append Transforms element
    if (!allTransforms.isEmpty()) {
        Element transformsElem = DOMUtils.createElement(ownerDoc,
                                                        "Transforms",
                                                        XMLSignature.XMLNS,
                                                        dsPrefix);
        refElem.appendChild(transformsElem);
        for (Transform transform : allTransforms) {
            ((DOMStructure)transform).marshal(transformsElem,
                                              dsPrefix, context);
        }
    }

    // create and append DigestMethod element
    ((DOMDigestMethod)digestMethod).marshal(refElem, dsPrefix, context);

    // create and append DigestValue element
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Adding digestValueElem");
    }
    Element digestValueElem = DOMUtils.createElement(ownerDoc,
                                                     "DigestValue",
                                                     XMLSignature.XMLNS,
                                                     dsPrefix);
    if (digestValue != null) {
        digestValueElem.appendChild
            (ownerDoc.createTextNode(Base64.encode(digestValue)));
    }
    refElem.appendChild(digestValueElem);

    parent.appendChild(refElem);
    here = refElem.getAttributeNodeNS(null, "URI");
}
 
Example 20
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 doc contains one entity and one entity
 * reference, <br>
 * <b>name</b>: entities <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: the entity and the entity reference are removed
 */
@Test
public void testEntities002() {
    Document doc = null;
    try {
        doc = loadDocument(null, test1_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("entities", Boolean.FALSE)) {
        Assert.fail("setting 'entities' to false is not supported");
    }

    Element root = doc.getDocumentElement();
    root.appendChild(doc.createEntityReference("x"));

    // TODO: remove debug
    NamedNodeMap entities = doc.getDoctype().getEntities();
    Entity entityX = (Entity) entities.getNamedItem("x");
    System.err.println();
    System.err.println("Entity x: " + entityX.getTextContent());
    System.err.println();

    config.setParameter("entities", Boolean.FALSE);

    setHandler(doc);
    doc.normalizeDocument();
    Node child = root.getFirstChild();

    // TODO: restore test, exclude for now to allow other tests to run
    /*
     * if (child == null) { fail("root has no child"); } if
     * (child.getNodeType() != Node.TEXT_NODE ||
     * !"X".equals(child.getNodeValue())) { fail("root's child is " + child
     * + ", expected text node with value 'X'"); }
     *
     * if (doc.getDoctype() == null) { fail("no doctype found"); }
     *
     * if (doc.getDoctype().getEntities() != null &&
     * doc.getDoctype().getEntities().getNamedItem("x") != null) {
     * fail("entity with name 'x' is found, expected to be removed"); }
     */

    return; // Status.passed("OK");
}