Example usage for org.w3c.dom Element setAttributeNode

List of usage examples for org.w3c.dom Element setAttributeNode

Introduction

In this page you can find the example usage for org.w3c.dom Element setAttributeNode.

Prototype

public Attr setAttributeNode(Attr newAttr) throws DOMException;

Source Link

Document

Adds a new attribute node.

Usage

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static void copyContent(Element source, Element destination) {
    NamedNodeMap attributes = source.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        Attr clone = (Attr) attr.cloneNode(true);
        destination.setAttributeNode(clone);
    }/*from w ww  . j  a va2 s .  c  om*/
    NodeList childNodes = source.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node item = childNodes.item(i);
        destination.appendChild(item);
    }
}

From source file:com.marklogic.dom.ElementImpl.java

protected Node cloneNode(Document doc, boolean deep) {
    Element elem = doc.createElementNS(getNamespaceURI(), getTagName());
    elem.setPrefix(getPrefix());/*  ww w  .j  a  va 2 s .com*/

    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (attr instanceof AttrImpl) {
            elem.setAttributeNode((Attr) ((AttrImpl) attr).cloneNode(doc, deep));
        } else {
            // ns decl, stored as Java DOM Attr
            // uri of xmlns is "http://www.w3.org/2000/xmlns/"
            Attr clonedAttr = doc.createAttributeNS("http://www.w3.org/2000/xmlns/", attr.getName());
            clonedAttr.setValue(attr.getValue());
            elem.setAttributeNode(clonedAttr);
        }
    }

    if (deep) {
        // clone children
        NodeList list = getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            NodeImpl n = (NodeImpl) list.item(i);
            Node c = n.cloneNode(doc, true);
            elem.appendChild(c);
        }
    }
    return elem;
}

From source file:clus.ext.hierarchical.WHTDStatistic.java

@Override
public Element getPredictElement(Document doc) {
    Element stats = doc.createElement("WHTDStat");
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    Attr examples = doc.createAttribute("examples");
    examples.setValue(fr.format(m_SumWeight));
    stats.setAttributeNode(examples);
    if (m_Threshold >= 0.0) {
        String pred = computePrintTuple().toStringHuman(getHier());
        Element predictions = doc.createElement("Predictions");
        stats.appendChild(predictions);//  ww w.  java  2  s .  c o m
        String[] predictionS = pred.split(",");
        for (String prediction : predictionS) {
            Element attr = doc.createElement("Prediction");
            predictions.appendChild(attr);
            attr.setTextContent(prediction);
        }
    } else {
        for (int i = 0; i < m_NbAttrs; i++) {
            Element attr = doc.createElement("Target");
            Attr name = doc.createAttribute("name");
            name.setValue(m_Attrs[i].getName());
            attr.setAttributeNode(name);
            if (m_SumWeight == 0.0) {
                attr.setTextContent("?");
            } else {
                attr.setTextContent(fr.format(getMean(i)));
            }
            stats.appendChild(attr);
        }
    }
    return stats;
}

From source file:com.hydroLibCreator.action.Creator.java

private void buildDrumKitXML() {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*w  ww  .  ja  v a2 s  .com*/
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException parserException) {
        parserException.printStackTrace();
    }

    Element drumkit_info = document.createElement("drumkit_info");
    document.appendChild(drumkit_info);

    Attr xmlns = document.createAttribute("xmlns");
    xmlns.setValue("http://www.hydrogen-music.org/drumkit");

    Attr xmlns_xsi = document.createAttribute("xmlns:xsi");
    xmlns_xsi.setValue("http://www.w3.org/2001/XMLSchema-instance");

    drumkit_info.setAttributeNode(xmlns);
    drumkit_info.setAttributeNode(xmlns_xsi);

    Node nameNode = createNameNode(document);
    drumkit_info.appendChild(nameNode);

    Node authorNode = createAuthorNode(document);
    drumkit_info.appendChild(authorNode);

    Node infoNode = createInfoNode(document);
    drumkit_info.appendChild(infoNode);

    Node licenseNode = createLicenseNode(document);
    drumkit_info.appendChild(licenseNode);

    Node instrumentListNode = createInstrumentListNode(document);
    drumkit_info.appendChild(instrumentListNode);

    // write the XML document to disk
    try {

        // create DOMSource for source XML document
        Source xmlSource = new DOMSource(document);

        // create StreamResult for transformation result
        Result result = new StreamResult(new FileOutputStream(destinationPath + "/drumkit.xml"));

        // create TransformerFactory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // create Transformer for transformation
        Transformer transformer = transformerFactory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        // transform and deliver content to client
        transformer.transform(xmlSource, result);
    }

    // handle exception creating TransformerFactory
    catch (TransformerFactoryConfigurationError factoryError) {
        System.err.println("Error creating " + "TransformerFactory");
        factoryError.printStackTrace();
    } catch (TransformerException transformerError) {
        System.err.println("Error transforming document");
        transformerError.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

From source file:Interface.MainJFrame.java

private void btnXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXMLActionPerformed
    // TODO add your handling code here:
    try {//from  w  w  w .  j  ava2 s  .  c o  m

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Employees");
        doc.appendChild(rootElement);

        // staff elements
        String empTitle = txtEmployeeType.getText().trim();
        empTitle = empTitle.replace(" ", "");
        Element staff = doc.createElement(empTitle);
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("ID");
        attr.setValue(txtEmployeeID.getText().trim());
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // FullName elements
        Element FulllName = doc.createElement("FulllName");
        FulllName.appendChild(doc.createTextNode(txtFullName.getText().trim()));
        staff.appendChild(FulllName);

        // Phone elements
        Element Phone = doc.createElement("PhoneNumber");
        Phone.appendChild(doc.createTextNode(txtPhoneNumber.getText().trim()));
        staff.appendChild(Phone);

        // Address elements
        Element Address = doc.createElement("Address");
        Address.appendChild(doc.createTextNode(txtAddress.getText().trim()));
        staff.appendChild(Address);

        // Title elements
        Element Title = doc.createElement("Tile");
        Title.appendChild(doc.createTextNode(txtEmployeeType.getText().trim()));
        staff.appendChild(Title);

        // PayCategory elements
        Element PayCategory = doc.createElement("PayCategory");
        PayCategory.appendChild(doc.createTextNode(txtPayCategory.getText().trim()));
        staff.appendChild(PayCategory);

        // Salary elements
        Element Salary = doc.createElement("Salary");
        Salary.appendChild(doc.createTextNode(txtSalary.getText().trim()));
        staff.appendChild(Salary);

        // Hours elements

        String hours = txtHours.getText().trim();
        if (txtHours.getText().equalsIgnoreCase("") || hours == null) {
            hours = "null";
        }
        Element Hours = doc.createElement("Hours");
        Hours.appendChild(doc.createTextNode(hours));
        staff.appendChild(Hours);

        // Bonus elements
        Element Bonus = doc.createElement("Bonus");
        Bonus.appendChild(doc.createTextNode(txtBonuses.getText().trim()));
        staff.appendChild(Bonus);

        // Total elements
        Element Total = doc.createElement("Total");
        Total.appendChild(doc.createTextNode(txtTotal.getText().trim()));
        staff.appendChild(Total);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("XMLOutput"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    }

}

From source file:de.uzk.hki.da.metadata.MetadataStructure.java

private void addNewElementToParent(PreservationSystem preservationSystem, String id, String elementName,
        String elementValue, Element parent, Document edmDoc) {
    Element eName = edmDoc.createElement(elementName);
    if (elementName.equals(C.EDM_HAS_VIEW) || elementName.equals(C.EDM_IS_PART_OF)
            || elementName.equals(C.EDM_HAS_PART) || elementName.equals(C.EDM_IS_SHOWN_BY)
            || elementName.equals(C.EDM_OBJECT)) {
        if (elementName.equals(C.EDM_IS_PART_OF) || elementName.equals(C.EDM_HAS_PART)) {
            elementValue = preservationSystem.getUrisCho() + "/" + elementValue;
        }//from  w  w w.j  a  v  a 2s.  com
        Attr rdfResource = edmDoc.createAttribute("rdf:resource");
        rdfResource.setValue(elementValue);
        eName.setAttributeNode(rdfResource);
    } else {
        eName.appendChild(edmDoc.createTextNode(elementValue));
    }
    parent.appendChild(eName);
}

From source file:clus.statistic.ClassificationStat.java

@Override
public Element getPredictElement(Document doc) {
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    Element stats = doc.createElement("ClassificationStat");
    Attr examples = doc.createAttribute("examples");
    examples.setValue(fr.format(m_SumWeight));
    stats.setAttributeNode(examples);
    Element majorities = doc.createElement("MajorityClasses");
    stats.appendChild(majorities);/*from w  w w  .java 2s .  co m*/
    if (m_MajorityClasses != null) {
        for (int i = 0; i < m_NbTarget; i++) {
            Element majority = doc.createElement("Target");
            majorities.appendChild(majority);

            majority.setTextContent(m_Attrs[i].getValue(m_MajorityClasses[i]));

            Attr name = doc.createAttribute("name");
            name.setValue(m_Attrs[i].getName());
            majority.setAttributeNode(name);
        }
    } else {
        Element majority = doc.createElement("Attribute");
        majorities.appendChild(majority);
    }
    Element distribution = doc.createElement("Distributions");
    stats.appendChild(distribution);
    for (int j = 0; j < m_NbTarget; j++) {
        Element target = doc.createElement("Target");
        distribution.appendChild(target);
        Attr name = doc.createAttribute("name");
        name.setValue(m_Attrs[j] + "");
        target.setAttributeNode(name);
        for (int i = 0; i < m_ClassCounts[j].length; i++) {
            Element value = doc.createElement("Value");
            target.appendChild(value);
            name = doc.createAttribute("name");
            name.setValue(m_Attrs[j].getValue(i));
            value.setAttributeNode(name);
            value.setTextContent(m_ClassCounts[j][i] + "");
        }
    }
    return stats;
}

From source file:com.amalto.core.storage.hibernate.MappingGenerator.java

private void generatorSubType(ComplexTypeMetadata parentComplexType, Element classElement) {
    boolean wasGeneratingConstraints;
    // Sub types/* w  ww. j  a  v  a2 s.  c  o  m*/
    if (!parentComplexType.getDirectSubTypes().isEmpty()) {
        if (parentComplexType.isInstantiable()) {
            /*
            <union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">
                   <property name="creditCardType" column=""/>
                   ...
               </union-subclass>
            */
            for (ComplexTypeMetadata subType : parentComplexType.getDirectSubTypes()) {
                Element unionSubclass = document.createElement("union-subclass"); //$NON-NLS-1$
                Attr name = document.createAttribute("name"); //$NON-NLS-1$
                name.setValue(ClassCreator.getClassName(subType.getName()));
                unionSubclass.setAttributeNode(name);

                Attr tableName = document.createAttribute("table"); //$NON-NLS-1$
                tableName.setValue(resolver.get(subType));
                unionSubclass.setAttributeNode(tableName);

                Collection<FieldMetadata> subTypeFields = subType.getFields();
                for (FieldMetadata subTypeField : subTypeFields) {
                    if (!parentComplexType.hasField(subTypeField.getName()) && !subTypeField.isKey()) {
                        unionSubclass.appendChild(subTypeField.accept(this));
                    }
                }
                if (!subType.getDirectSubTypes().isEmpty()) {
                    generatorSubType(subType, unionSubclass);
                }
                classElement.appendChild(unionSubclass);
            }
        } else {
            /*
            <subclass name="CreditCardPayment" discriminator-value="CREDIT">
                <property name="creditCardType" column="CCTYPE"/>
                ...
            </subclass>
             */
            wasGeneratingConstraints = generateConstrains;
            generateConstrains = false;
            try {
                for (ComplexTypeMetadata subType : parentComplexType.getDirectSubTypes()) {
                    Element subclass = document.createElement("subclass"); //$NON-NLS-1$
                    Attr name = document.createAttribute("name"); //$NON-NLS-1$
                    name.setValue(ClassCreator.getClassName(subType.getName()));
                    subclass.setAttributeNode(name);
                    Attr discriminator = document.createAttribute("discriminator-value"); //$NON-NLS-1$
                    discriminator.setValue(ClassCreator.PACKAGE_PREFIX + subType.getName());
                    subclass.setAttributeNode(discriminator);

                    Collection<FieldMetadata> subTypeFields = subType.getFields();
                    for (FieldMetadata subTypeField : subTypeFields) {
                        if (!parentComplexType.hasField(subTypeField.getName()) && !subTypeField.isKey()) {
                            subclass.appendChild(subTypeField.accept(this));
                        }
                    }
                    if (!subType.getDirectSubTypes().isEmpty()) {
                        generatorSubType(subType, subclass);
                    }
                    classElement.appendChild(subclass);
                }
            } finally {
                generateConstrains = wasGeneratingConstraints;
            }
        }
    }
}

From source file:com.amalto.core.storage.hibernate.MappingGenerator.java

@Override
public Element visit(ComplexTypeMetadata complexType) {
    if (complexType.getKeyFields().isEmpty()) {
        throw new IllegalArgumentException("Type '" + complexType.getName() + "' has no key."); //$NON-NLS-1$ //$NON-NLS-2$
    }//from  w w  w .j  a  v a  2s. c  o m
    if (!complexType.getSuperTypes().isEmpty()) {
        return null;
    }

    tableNames.push(resolver.get(complexType));
    Element classElement;
    {
        String generatedClassName = ClassCreator.getClassName(complexType.getName());
        classElement = document.createElement("class"); //$NON-NLS-1$
        Attr className = document.createAttribute("name"); //$NON-NLS-1$
        className.setValue(generatedClassName);
        classElement.getAttributes().setNamedItem(className);
        Attr classTable = document.createAttribute("table"); //$NON-NLS-1$
        classTable.setValue(tableNames.peek());
        classElement.getAttributes().setNamedItem(classTable);
        // Adds schema name (if set in configuration)
        String value = dataSource.getAdvancedProperties().get("hibernate.default_schema"); //$NON-NLS-1
        if (value != null) {
            Attr classSchema = document.createAttribute("schema"); //$NON-NLS-1$
            classSchema.setValue(value);
            classElement.getAttributes().setNamedItem(classSchema);
        }
        // dynamic-update="true"
        Attr dynamicUpdate = document.createAttribute("dynamic-update"); //$NON-NLS-1$
        dynamicUpdate.setValue("true"); //$NON-NLS-1$
        classElement.getAttributes().setNamedItem(dynamicUpdate);
        // dynamic-insert="true"
        Attr dynamicInsert = document.createAttribute("dynamic-insert"); //$NON-NLS-1$
        dynamicInsert.setValue("true"); //$NON-NLS-1$
        classElement.getAttributes().setNamedItem(dynamicInsert);
        // <cache usage="read-write" include="non-lazy"/>
        Element cacheElement = document.createElement("cache"); //$NON-NLS-1$
        Attr usageAttribute = document.createAttribute("usage"); //$NON-NLS-1$
        usageAttribute.setValue("read-write"); //$NON-NLS-1$
        cacheElement.getAttributes().setNamedItem(usageAttribute);
        Attr includeAttribute = document.createAttribute("include"); //$NON-NLS-1$
        includeAttribute.setValue("non-lazy"); //$NON-NLS-1$
        cacheElement.getAttributes().setNamedItem(includeAttribute);
        Attr regionAttribute = document.createAttribute("region"); //$NON-NLS-1$
        regionAttribute.setValue("region"); //$NON-NLS-1$
        cacheElement.getAttributes().setNamedItem(regionAttribute);
        classElement.appendChild(cacheElement);

        Collection<FieldMetadata> keyFields = complexType.getKeyFields();
        List<FieldMetadata> allFields = new ArrayList<FieldMetadata>(complexType.getFields());

        // Process key fields first (Hibernate DTD enforces IDs to be declared first in <class/> element).
        Element idParentElement = classElement;
        if (keyFields.size() > 1) {
            /*
            <composite-id>
                    <key-property column="x_enterprise" name="x_enterprise"/>
                    <key-property column="x_id" name="x_id"/>
                </composite-id>
             */
            compositeId = true;
            idParentElement = document.createElement("composite-id"); //$NON-NLS-1$
            classElement.appendChild(idParentElement);

            Attr classAttribute = document.createAttribute("class"); //$NON-NLS-1$
            classAttribute.setValue(generatedClassName + "_ID"); //$NON-NLS-1$
            idParentElement.getAttributes().setNamedItem(classAttribute);

            Attr mappedAttribute = document.createAttribute("mapped"); //$NON-NLS-1$
            mappedAttribute.setValue("true"); //$NON-NLS-1$
            idParentElement.getAttributes().setNamedItem(mappedAttribute);
        }
        for (FieldMetadata keyField : keyFields) {
            idParentElement.appendChild(keyField.accept(this));
            boolean wasRemoved = allFields.remove(keyField);
            if (!wasRemoved) {
                LOGGER.error(
                        "Field '" + keyField.getName() + "' was expected to be removed from processed fields."); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
        compositeId = false;
        // Generate a discriminator (if needed).
        if (!complexType.getSubTypes().isEmpty() && !complexType.isInstantiable()) {
            // <discriminator column="PAYMENT_TYPE" type="string"/>
            Element discriminator = document.createElement("discriminator"); //$NON-NLS-1$
            Attr name = document.createAttribute("column"); //$NON-NLS-1$
            name.setValue(DISCRIMINATOR_NAME);
            discriminator.setAttributeNode(name);
            Attr type = document.createAttribute("type"); //$NON-NLS-1$
            type.setValue("string"); //$NON-NLS-1$
            discriminator.setAttributeNode(type);
            classElement.appendChild(discriminator);
        }
        // Process this type fields
        boolean wasGeneratingConstraints = generateConstrains;
        try {
            if (complexType.getName().startsWith("X_")) { //$NON-NLS-1$
                Integer usageNumber = complexType.<Integer>getData(TypeMapping.USAGE_NUMBER);
                // TMDM-8283: Don't turn on constraint generation even if reusable type is used only once.
                generateConstrains = generateConstrains && (usageNumber == null || usageNumber <= 1);
            }
            for (FieldMetadata currentField : allFields) {
                Element child = currentField.accept(this);
                if (child == null) {
                    throw new IllegalArgumentException(
                            "Field type " + currentField.getClass().getName() + " is not supported."); //$NON-NLS-1$ //$NON-NLS-2$
                }
                classElement.appendChild(child);
            }
        } finally {
            generateConstrains = wasGeneratingConstraints;
        }
        // Sub types
        generatorSubType(complexType, classElement);
    }
    tableNames.pop();

    return classElement;
}

From source file:ar.edu.uns.cs.vyglab.arq.rockar.gui.JFrameControlPanel.java

public void saveTable() {
    File currentDir = new File(System.getProperty("user.dir"));
    JFileChooser saveDialog = new JFileChooser(currentDir);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MTF File", "mtf", "mtf");
    saveDialog.setFileFilter(filter);//  ww w.j av a2  s  .c om
    int response = saveDialog.showSaveDialog(this);
    if (response == saveDialog.APPROVE_OPTION) {
        File file = saveDialog.getSelectedFile();
        if (file.getName().lastIndexOf(".") == -1) {
            file = new File(file.getName() + ".mtf");
        }
        DataCenter.fileMineralList = file;
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("table");
            doc.appendChild(rootElement);

            // para cada mineral en la tabla de minerales, agrego un Element
            for (int i = 0; i < this.jTableMineralsModel.getRowCount(); i++) {
                Element mineral = doc.createElement("mineral");

                // set attribute id to mineral element
                Attr attr = doc.createAttribute("key");
                //attr.setValue(this.jTableMinerales.getModel().getValueAt(i, 0).toString());
                attr.setValue(this.jTableMineralsModel.getValueAt(i, 0).toString());
                mineral.setAttributeNode(attr);

                // set attribute name to mineral element
                attr = doc.createAttribute("name");
                attr.setValue(this.jTableMineralsModel.getValueAt(i, 1).toString());
                mineral.setAttributeNode(attr);

                // set attribute color to mineral element
                attr = doc.createAttribute("color");
                attr.setValue(String.valueOf(((Color) this.jTableMineralsModel.getValueAt(i, 2)).getRGB()));
                mineral.setAttributeNode(attr);

                // agrego el mineral a los minerales
                rootElement.appendChild(mineral);
            }

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(DataCenter.fileMineralList);

            transformer.transform(source, result);

        } catch (Exception e) {
        }
    }
}