Example usage for org.jdom2 Element setAttribute

List of usage examples for org.jdom2 Element setAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element setAttribute.

Prototype

public Element setAttribute(final Attribute attribute) 

Source Link

Document

This sets an attribute value for this element.

Usage

From source file:com.sun.syndication.io.impl.DCModuleGenerator.java

License:Open Source License

/**
 * Utility method to generate an element for a subject.
 * <p>//from  ww  w.j  av a 2  s.c om
 * @param subject the subject to generate an element for.
 * @return the element for the subject.
 */
protected final Element generateSubjectElement(DCSubject subject) {
    Element subjectElement = new Element("subject", getDCNamespace());

    if (subject.getTaxonomyUri() != null) {
        Element descriptionElement = new Element("Description", getRDFNamespace());
        Element topicElement = new Element("topic", getTaxonomyNamespace());
        Attribute resourceAttribute = new Attribute("resource", subject.getTaxonomyUri(), getRDFNamespace());
        topicElement.setAttribute(resourceAttribute);
        descriptionElement.addContent(topicElement);

        if (subject.getValue() != null) {
            Element valueElement = new Element("value", getRDFNamespace());
            valueElement.addContent(subject.getValue());
            descriptionElement.addContent(valueElement);
        }
        subjectElement.addContent(descriptionElement);
    } else {
        subjectElement.addContent(subject.getValue());
    }
    return subjectElement;
}

From source file:com.sun.syndication.io.impl.RSS091UserlandGenerator.java

License:Open Source License

protected Element createRootElement(Channel channel) {
    Element root = new Element("rss", getFeedNamespace());
    Attribute version = new Attribute("version", getVersion());
    root.setAttribute(version);
    root.addNamespaceDeclaration(getContentNamespace());
    generateModuleNamespaceDefs(root);/*from  w w  w.ja  v  a  2 s . c  om*/

    return root;
}

From source file:com.sun.syndication.io.impl.RSS092Generator.java

License:Open Source License

protected Element generateCloud(Cloud cloud) {
    Element eCloud = new Element("cloud", getFeedNamespace());

    if (cloud.getDomain() != null) {
        eCloud.setAttribute(new Attribute("domain", cloud.getDomain()));
    }/*ww w  . jav a 2  s  .  co m*/

    if (cloud.getPort() != 0) {
        eCloud.setAttribute(new Attribute("port", String.valueOf(cloud.getPort())));
    }

    if (cloud.getPath() != null) {
        eCloud.setAttribute(new Attribute("path", cloud.getPath()));
    }

    if (cloud.getRegisterProcedure() != null) {
        eCloud.setAttribute(new Attribute("registerProcedure", cloud.getRegisterProcedure()));
    }

    if (cloud.getProtocol() != null) {
        eCloud.setAttribute(new Attribute("protocol", cloud.getProtocol()));
    }
    return eCloud;
}

From source file:com.sun.syndication.io.impl.RSS092Generator.java

License:Open Source License

protected Element generateSourceElement(Source source) {
    Element sourceElement = new Element("source", getFeedNamespace());
    if (source.getUrl() != null) {
        sourceElement.setAttribute(new Attribute("url", source.getUrl()));
    }/*from  www  .  j  a  v a 2 s .c o m*/
    sourceElement.addContent(source.getValue());
    return sourceElement;
}

From source file:com.sun.syndication.io.impl.RSS094Generator.java

License:Open Source License

protected void populateItem(Item item, Element eItem, int index) {
    super.populateItem(item, eItem, index);

    Description description = item.getDescription();
    if (description != null && description.getType() != null) {
        Element eDescription = eItem.getChild("description", getFeedNamespace());
        eDescription.setAttribute(new Attribute("type", description.getType()));
    }/*from w ww .j  a  v  a 2s. c o m*/
    eItem.removeChild("expirationDate", getFeedNamespace());
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.modules.AbstractModule.java

License:Apache License

protected void replaceElement(final Element toReplace, final String replacementName) {
    assert toReplace != null && replacementName != null;
    assert !replacementName.isEmpty();
    final Element parent = toReplace.getParentElement();
    assert parent != null;
    final Element replacement = new Element(replacementName);
    replacement.addContent(toReplace.removeContent());
    final List<Attribute> attributes = toReplace.getAttributes();
    for (Attribute attribute : attributes) {
        replacement.setAttribute(attribute.detach());
    }//from  ww w.j  a v a2s.co  m
    final int parentIndex = parent.indexOf(toReplace);
    parent.removeContent(parentIndex);
    parent.addContent(parentIndex, replacement);
    LOGGER.log(Level.FINE, "{0} replaced with {1}", new Object[] { toReplace, replacementName });
}

From source file:de.herm_detlef.java.application.io.Export.java

License:Apache License

private static Document createJdomDocument(ObservableList<ExerciseItem> exerciseItemList) {

    Namespace ns = Namespace.getNamespace(ApplicationConstants.XML_NAMESPACE);
    Element catalog = new Element(TAG.CATALOG.name(), ns);
    Document doc = new Document(catalog);
    Namespace xsi = Namespace.getNamespace("xsi", ApplicationConstants.XML_SCHEMA_INSTANCE);
    doc.getRootElement().addNamespaceDeclaration(xsi);
    doc.getRootElement().setAttribute("schemaLocation", ApplicationConstants.XML_SCHEMA_DEFINITION, xsi);

    int count = 0;
    for (ExerciseItem exItem : exerciseItemList) {

        Element item = new Element(TAG.ITEM.name(), ns);
        catalog.addContent(item);/*ww w .  j ava 2s  .c o  m*/

        Element id = new Element(TAG.ID.name(), ns);
        id.addContent(String.valueOf(++count));
        item.addContent(id);

        Element element = null;

        for (ItemPart itemPart : exItem.getExerciseItemParts()) {
            Object obj = itemPart.get();

            if (obj == null) {
                // assert false : String.format(
                // "%s",
                // itemPart.getClass() ); // TODO
                continue;
            }

            if (itemPart instanceof QuestionText || itemPart instanceof QuestionText2) {
                isAnswerPart = false;

                if (!isQuestionPart) {
                    element = new Element(TAG.QUESTION.name(), ns);
                    item.addContent(element);
                    isQuestionPart = true;
                }

                if (element == null)
                    continue;

                if (itemPart instanceof QuestionText) {
                    Element text = new Element(TAG.TEXT.name(), ns);
                    element.addContent(text);
                    text.addContent(((QuestionText) itemPart).getStr().get());
                }

                if (itemPart instanceof QuestionText2) {
                    Element text = new Element(TAG.TEXT2.name(), ns);
                    element.addContent(text);
                    text.addContent(((QuestionText2) itemPart).getStr().get());
                }
            }

            else if (itemPart instanceof QuestionCode) {
                isAnswerPart = false;

                if (!isQuestionPart) {
                    element = new Element(TAG.QUESTION.name(), ns);
                    item.addContent(element);
                    isQuestionPart = true;
                }

                if (element == null)
                    continue;

                Element code = new Element(TAG.CODE.name(), ns);
                element.addContent(code);

                code.addContent(((QuestionCode) itemPart).getStr().get());
            }

            else if (itemPart instanceof SingleChoiceAnswerText) {
                isQuestionPart = false;

                if (!isAnswerPart) {
                    element = new Element(TAG.SINGLE_CHOICE_ANSWER.name(), ns);
                    item.addContent(element);
                    isAnswerPart = true;
                }

                if (element == null)
                    continue;

                Element answer = new Element(TAG.TEXT.name(), ns);
                element.addContent(answer);

                if (((AnswerText) itemPart).isMarked()) {
                    Attribute mark = new Attribute("mark", "true");
                    answer.setAttribute(mark);
                }

                answer.addContent(((SingleChoiceAnswerText) itemPart).getStr().get());
            }

            else if (itemPart instanceof MultipleChoiceAnswerText) {
                isQuestionPart = false;

                if (!isAnswerPart) {
                    element = new Element(TAG.MULTIPLE_CHOICE_ANSWER.name(), ns);
                    item.addContent(element);
                    isAnswerPart = true;
                }

                if (element == null)
                    continue;

                Element answer = new Element(TAG.TEXT.name(), ns);
                element.addContent(answer);

                if (((AnswerText) itemPart).isMarked()) {
                    Attribute mark = new Attribute("mark", "true");
                    answer.setAttribute(mark);
                }

                answer.addContent(((MultipleChoiceAnswerText) itemPart).getStr().get());
            }

            else if (itemPart instanceof SolutionText) {
                isQuestionPart = false;
                isAnswerPart = false;

                element = new Element(TAG.SOLUTION.name(), ns);
                item.addContent(element);

                Element solution = new Element(TAG.TEXT.name(), ns);
                element.addContent(solution);

                solution.addContent(((SolutionText) itemPart).getStr().get());
            }

            if (element == null) {
                assert false;
                return null;
            }
        }
    }

    return doc;
}

From source file:de.knowwe.visualization.dot.DOTRenderer.java

License:Open Source License

/**
 * Adds the target-attribute to the element.
 *
 * @created 21.12.2013/*from   www.  j av  a 2  s . c om*/
 */
private static void addTargetAttribute(Element element) {
    Attribute target = new Attribute("target", "_top");
    element.setAttribute(target);
}

From source file:edu.utep.cs.jasg.apiGenerator.APIGenerator.java

License:Open Source License

/** Creates JDom nodes of the parser rules */
private void createRuleElements() {
    Element ruleSet = new Element("rule_set");
    Iterator<String> keys = parserModel.getRuleTypes().keySet().iterator();

    while (keys.hasNext()) {
        Element rule = new Element("rule");
        String key = keys.next();

        rule.setAttribute(new Attribute("name", key));
        rule.setAttribute(new Attribute("type", parserModel.getRuleTypes().get(key)));
        rule.addContent(createRuleDefinitions(key));
        ruleSet.addContent(rule);/*w ww .jav a 2s.c  o  m*/
    }

    doc.getRootElement().addContent(ruleSet);
}

From source file:es.upm.dit.xsdinferencer.generation.generatorimpl.schemageneration.XMLSchemaDocumentGenerator.java

License:Apache License

/**
 * It generates the XSD file of the targetNamespace given at the constructor, taking into account that 
 * the main namespace is the one given at the constructor.
 * //from w w w  . ja  v a2s  .c  om
 * @param schema the schema object
 * @param configuration the inference configuration
 * 
 * @return a JDOM2 {@link Document} object containing the XSD contents.
 * 
 * @see SchemaDocumentGenerator#generateSchemaDocument(Schema, XSDInferenceConfiguration)
 */
@Override
public Document generateSchemaDocument(Schema schema, XSDInferenceConfiguration configuration) {
    //      if(!configuration.getElementsGlobal()==false || 
    //            !configuration.getComplexTypesGlobal()==true ||
    //            !configuration.getSimpleTypesGlobal()==true
    //            )
    //         throw new UnsupportedOperationException("Not implemented yet.");
    //
    checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(mainNamespace),
            "The main namespace must be a known namespace");
    checkArgument(schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(targetNamespace),
            "The target namespace must be a known namespace");
    //      checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSD_NAMESPACE_URI),"The XSD namespace must not be a known namespace");
    //      checkArgument(!schema.getNamespacesToPossiblePrefixMappingModifiable().containsKey(XSI_NAMESPACE_URI),"The XSI namespace must not be a known namespace");
    Map<String, String> namespaceURIToPrefixMappings = schema.getSolvedNamespaceMappings();
    if (configuration.getSkipNamespaces().contains(targetNamespace)) {
        throw new IllegalArgumentException("This is an skipped namespace, so its XSD should not be generated");
    }
    if (targetNamespace.equals(XSD_NAMESPACE_URI))
        System.err.println(
                "The XML Schema namespace is being considered as a target namespace in your documents. Independing of the inferred schemas, the only valid XSD for an XSD would be the normative one present at its first RFC");
    Namespace xsdNamespace = Namespace.getNamespace(XSD_NAMESPACE_PREFIX.replace(":", ""), XSD_NAMESPACE_URI);
    List<Namespace> namespaceDeclarations = getNamespaceDeclarations(namespaceURIToPrefixMappings,
            xsdNamespace);
    Element elementSchema = new Element("schema", xsdNamespace);
    for (int i = 0; i < namespaceDeclarations.size(); i++) {
        Namespace currentNamespace = namespaceDeclarations.get(i);
        elementSchema.addNamespaceDeclaration(currentNamespace);
        String currentNamespaceUri = currentNamespace.getURI();
        if (!targetNamespace.equals(mainNamespace) && !currentNamespaceUri.equals(mainNamespace))
            continue;
        if (currentNamespace.equals(Namespace.XML_NAMESPACE)
                && (!schema.getAttributes().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI)
                        && !schema.getElements().containsRow(XSDInferenceConfiguration.XML_NAMESPACE_URI))) {
            continue;
        }
        if (currentNamespaceUri.equals(XSD_NAMESPACE_URI)
                && !namespaceURIToPrefixMappings.containsKey(XSD_NAMESPACE_URI))
            continue;
        if (targetNamespace.equals(currentNamespaceUri)
                || (currentNamespaceUri.equals("") && (fileNameGenerator == null)))
            continue;
        if (currentNamespaceUri.equals("") && !currentNamespaceUri.equals(mainNamespace)
                && !schema.getElements().containsRow(""))
            continue;
        Element importElement = new Element("import", xsdNamespace);
        if (!currentNamespaceUri.equals("")) {
            Attribute namespaceAttr = new Attribute("namespace", currentNamespaceUri);
            importElement.setAttribute(namespaceAttr);
        }
        if (fileNameGenerator != null && !configuration.getSkipNamespaces().contains(currentNamespaceUri)) {
            String fileName = fileNameGenerator.getSchemaDocumentFileName(currentNamespaceUri,
                    namespaceURIToPrefixMappings);
            Attribute schemaLocationAttr = new Attribute("schemaLocation", fileName);
            importElement.setAttribute(schemaLocationAttr);
        }
        elementSchema.addContent(importElement);
    }

    if (!targetNamespace.equals("")) {
        Attribute targetNamespaceAttr = new Attribute("targetNamespace", targetNamespace);
        elementSchema.setAttribute(targetNamespaceAttr);
    }
    SortedSet<SimpleType> sortedSimpleTypes = new TreeSet<>(new SimpleTypeComparator());
    sortedSimpleTypes.addAll(schema.getSimpleTypes().values());
    SortedSet<ComplexType> sortedComplexTypes = new TreeSet<>(new ComplexTypeComparator());
    sortedComplexTypes.addAll(schema.getComplexTypes().values());
    //CONTINUE FROM HERE: Generate sorted sets for SchemaElement and SchemaAttribute objects and use them where needed.
    Attribute elementFormDefault = new Attribute("elementFormDefault", "qualified");
    elementSchema.setAttribute(elementFormDefault);
    Document resultingDocument = new Document(elementSchema);
    if (targetNamespace.equals(mainNamespace)) {
        //First, we declare global SimpleTypes.
        //If simpleTypesGlobal is true, any enumeration will be declared as a global simple type.
        //if not, simple types of complex types which have attributes but not children will be declared globally 
        //(due to limitations of XSD, they may not be declared locally together with the attributes info)
        if (configuration.getSimpleTypesGlobal()) {
            for (SimpleType simpleType : sortedSimpleTypes) {
                if (!simpleType.isEnum() || simpleType.isEmpty())
                    continue;
                Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace);
                elementSchema.addContent(simpleTypeElement);
            }
        } else {
            for (ComplexType complexType : sortedComplexTypes) {
                SimpleType simpleType = complexType.getTextSimpleType();
                if (complexType.getAttributeList().isEmpty() || !(complexType.getAutomaton().nodeCount() == 0)
                        || !simpleType.isEnum() || simpleType.isEmpty())
                    continue;
                Element simpleTypeElement = generateSimpleType(simpleType, false, configuration, xsdNamespace);
                elementSchema.addContent(simpleTypeElement);
            }
        }
        //Global complexType elements are only generated in the main schema (i.e. the one whose targetNamespace is equal to mainNamespace)
        if (configuration.getComplexTypesGlobal()) {
            for (ComplexType complexType : sortedComplexTypes) {
                boolean hasNoChildren = complexType.getRegularExpression().equals(new EmptyRegularExpression());
                boolean hasNoAttributes = complexType.getAttributeList().size() == 0;
                boolean hasNoComments = complexType.getComments().size() == 0;
                //               boolean simpleTypeIsNotEmpty = !complexType.getTextSimpleType().isEmpty();
                boolean simpleTypeIsWhiteSpaceOnlyOrEmpty = !(complexType.getTextSimpleType().isEmpty()
                        || complexType.getTextSimpleType().consistOnlyOfWhitespaceCharacters());
                if (hasNoChildren && hasNoAttributes && simpleTypeIsWhiteSpaceOnlyOrEmpty && hasNoComments)
                    continue; //Because the elements which are linked to this ComplexType at our internal model 
                              //will be linked to an XSD simple type elsewhere, either a builtin or a custom one.
                Element complexTypeElement = generateComplexType(configuration, complexType, false,
                        targetNamespace, namespaceURIToPrefixMappings, mainNamespace, xsdNamespace);
                elementSchema.addContent(complexTypeElement);
            }
        }
    }
    //If there are many namespaces and the workaround is disabled, we must declare global attributes.
    //If the targetNamespace is not the mainNamespace, we must declare all the attributes.
    //if the target namespace is the main namespace, we do not need to declare anything, because the complex types which hold the attributes 
    //are also in the main namespace.
    if ((namespaceURIToPrefixMappings.size() - configuration.getSkipNamespaces().size()) > 1) {

        SortedMap<String, SchemaAttribute> globalAttributeCandidates = new TreeMap<>(
                schema.getAttributes().row(targetNamespace));
        if (!targetNamespace.equals(mainNamespace) && !targetNamespace.equals("")) {
            globalAttributesLoop: for (Map.Entry<String, SchemaAttribute> schemaAttributeEntry : globalAttributeCandidates
                    .entrySet()) {
                SchemaAttribute schemaAttribute = schemaAttributeEntry.getValue();
                //First, we check if the attribute has been already declared when the workaround is disabled. 
                //If so, we update the "use" property.
                //The type should have been already merged.
                if (!configuration.getStrictValidRootDefinitionWorkaround()) {
                    List<Element> alreadyGeneratedAttributeElements = elementSchema.getChildren("attribute",
                            xsdNamespace);
                    for (int i = 0; i < alreadyGeneratedAttributeElements.size(); i++) {
                        Element currentAttributeElement = alreadyGeneratedAttributeElements.get(i);
                        if (currentAttributeElement.getAttributeValue("name")
                                .equals(schemaAttribute.getName())) {
                            continue globalAttributesLoop;
                        }
                    }
                }
                Element attributeOrAttributeGroupElement = generateAttribute(schemaAttribute, true,
                        configuration, namespaceURIToPrefixMappings, targetNamespace, mainNamespace,
                        schemaAttributeEntry.getKey(), xsdNamespace);
                elementSchema.addContent(attributeOrAttributeGroupElement);
            }
        }
    }

    //Now, we declare global elements.
    //An element will be declared globally if and only if: 
    //1-elementsGlobal is true in the configuration
    //2-The element is a valid root
    //3-The element is in a namespace other than the main namespace. Note that the element WILL be surrounded by the corresponding group if the workaround is enabled.
    //Another important remark: Iterating over a set copy implies iterating over DISTINCT SchemaElements, so if two keys pointed to equal SchemaElements, we would generate it only once-
    SortedSet<SchemaElement> schemaElementsAtTargetNamespace = new TreeSet<>(new SchemaElementComparator());
    schemaElementsAtTargetNamespace.addAll(schema.getElements().row(targetNamespace).values());
    globalSchemaElementsLoop: for (SchemaElement schemaElement : schemaElementsAtTargetNamespace) {
        //         if(!configuration.getElementsGlobal()&&
        //               !schemaElement.isValidRoot()&&
        //               (targetNamespace.equals(mainNamespace)||configuration.getStrictValidRootDefinitionWorkaround()))
        if (!configuration.getElementsGlobal() && !schemaElement.isValidRoot()
                && (targetNamespace.equals(mainNamespace)))
            continue;
        //         for(Element currentElement:elementSchema.getContent(Filters.element("element",xsdNamespace))){
        //            if(schemaElement.getName().equals(currentElement.getAttributeValue("name")))
        //               continue globalSchemaElementsLoop;
        //         }
        String possibleGroupName = schemaElement.getName() + configuration.getTypeNamesAncestorsSeparator()
                + schemaElement.getType().getName();
        for (Element currentElement : elementSchema.getContent(Filters.element("group", xsdNamespace))) {
            if (possibleGroupName.equals(currentElement.getAttributeValue("name")))
                continue globalSchemaElementsLoop;
        }
        Element elementOrGroupElement = generateElement(schemaElement, true, configuration, targetNamespace,
                mainNamespace, null, namespaceURIToPrefixMappings, xsdNamespace);
        if (elementOrGroupElement.getName().equals("element")) {
            for (Element currentElement : elementSchema.getChildren("element", xsdNamespace)) {
                if (schemaElement.getName().equals(currentElement.getAttributeValue("name")))
                    continue globalSchemaElementsLoop;
            }
        }
        elementSchema.addContent(elementOrGroupElement);
    }
    return resultingDocument;
}