Example usage for org.w3c.dom Document createTextNode

List of usage examples for org.w3c.dom Document createTextNode

Introduction

In this page you can find the example usage for org.w3c.dom Document createTextNode.

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:net.sf.jabref.logic.mods.MODSEntry.java

public Element getDOMrepresentation(Document d) {
    try {/*from   www  . j a va  2  s  .  c o  m*/
        Element mods = d.createElement(entryType);
        mods.setAttribute("version", "3.0");
        // mods.setAttribute("xmlns:xlink:", "http://www.w3.org/1999/xlink");
        // title
        if (title != null) {
            Element titleInfo = d.createElement("titleInfo");
            Element mainTitle = d.createElement("title");
            mainTitle.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(title)));
            titleInfo.appendChild(mainTitle);
            mods.appendChild(titleInfo);
        }
        if (authors != null) {
            for (PersonName name : authors) {
                Element modsName = d.createElement("name");
                modsName.setAttribute("type", "personal");
                if (name.getSurname() != null) {
                    Element namePart = d.createElement("namePart");
                    namePart.setAttribute("type", "family");
                    namePart.appendChild(
                            d.createTextNode(StringUtil.stripNonValidXMLCharacters(name.getSurname())));
                    modsName.appendChild(namePart);
                }
                if (name.getGivenNames() != null) {
                    Element namePart = d.createElement("namePart");
                    namePart.setAttribute("type", "given");
                    namePart.appendChild(
                            d.createTextNode(StringUtil.stripNonValidXMLCharacters(name.getGivenNames())));
                    modsName.appendChild(namePart);
                }
                Element role = d.createElement("role");
                Element roleTerm = d.createElement("roleTerm");
                roleTerm.setAttribute("type", "text");
                roleTerm.appendChild(d.createTextNode("author"));
                role.appendChild(roleTerm);
                modsName.appendChild(role);
                mods.appendChild(modsName);
            }
        }
        //publisher
        Element originInfo = d.createElement("originInfo");
        mods.appendChild(originInfo);
        if (this.publisher != null) {
            Element publisher = d.createElement(FieldName.PUBLISHER);
            publisher.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(this.publisher)));
            originInfo.appendChild(publisher);
        }
        if (date != null) {
            Element dateIssued = d.createElement("dateIssued");
            dateIssued.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(date)));
            originInfo.appendChild(dateIssued);
        }
        Element issuance = d.createElement("issuance");
        issuance.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(this.issuance)));
        originInfo.appendChild(issuance);

        if (id != null) {
            Element idref = d.createElement("identifier");
            idref.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(id)));
            mods.appendChild(idref);
            mods.setAttribute("ID", id);

        }
        Element typeOfResource = d.createElement("typeOfResource");
        String type = "text";
        typeOfResource.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(type)));
        mods.appendChild(typeOfResource);

        if (genre != null) {
            Element genreElement = d.createElement("genre");
            genreElement.setAttribute("authority", "marc");
            genreElement.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(genre)));
            mods.appendChild(genreElement);
        }

        if (host != null) {
            Element relatedItem = host.getDOMrepresentation(d);
            relatedItem.setAttribute("type", "host");
            mods.appendChild(relatedItem);
        }
        if (pages != null) {
            mods.appendChild(pages.getDOMrepresentation(d));
        }

        /* now generate extension fields for unhandled data */
        for (Map.Entry<String, String> theEntry : extensionFields.entrySet()) {
            Element extension = d.createElement("extension");
            String field = theEntry.getKey();
            String value = theEntry.getValue();
            if (handledExtensions.contains(field)) {
                continue;
            }
            Element theData = d.createElement(field);
            theData.appendChild(d.createTextNode(StringUtil.stripNonValidXMLCharacters(value)));
            extension.appendChild(theData);
            mods.appendChild(extension);
        }
        return mods;
    } catch (Exception e) {
        LOGGER.warn("Exception caught...", e);
        throw new Error(e);
    }
    // return result;
}

From source file:uk.co.markfrimston.tasktree.TaskTree.java

public void saveConfig() throws Exception {
    try {/*from  ww  w .ja  v  a  2  s  .  c om*/
        DocumentBuilder builder = builderFact.newDocumentBuilder();
        Document doc = builder.newDocument();
        //doc.appendChild(doc.createTextNode("\n"));
        Element elConfig = doc.createElement("config");
        doc.appendChild(elConfig);
        elConfig.appendChild(doc.createTextNode("\n"));

        makeConfigEl(doc, elConfig, "load-url", "URL used to load task tree from remote server", loadUrl);

        makeConfigEl(doc, elConfig, "save-url", "URL used to save task tree to remote server", saveUrl);

        makeConfigEl(doc, elConfig, "merge-command",
                "Command executed to merge task tree versions. " + "Use {0} for local file, {1} for remote",
                mergeCommand);

        if (lastSyncTime == null) {
            lastSyncTime = 0L;
        }
        makeConfigEl(doc, elConfig, "last-sync", "Timestamp of last sync. Do not edit!", lastSyncTime);

        if (unsynchedChanges == null) {
            unsynchedChanges = true;
        }
        makeConfigEl(doc, elConfig, "unsynched-changes", "Changes made since last sync. Do not edit!",
                unsynchedChanges);

        elConfig.appendChild(doc.createTextNode("\n"));

        makeFilePath();
        File file = new File(filePath + CONFIG_FILENAME);
        FileOutputStream fileStream = new FileOutputStream(file);
        writeDocToStream(doc, fileStream);
        fileStream.close();
    } catch (Exception e) {
        throw new Exception("Failed to save config file: " + e.getClass().getName() + " - " + e.getMessage());
    }
}

From source file:net.sourceforge.eclipsetrader.core.CurrencyConverter.java

private void save() {
    try {/*  w  w  w.j a v  a 2 s  . co m*/
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        for (Iterator iter = currencies.iterator(); iter.hasNext();) {
            Element node = document.createElement("currency"); //$NON-NLS-1$
            node.appendChild(document.createTextNode((String) iter.next()));
            root.appendChild(node);
        }

        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            String symbol = (String) iter.next();
            Element node = document.createElement("conversion"); //$NON-NLS-1$
            node.setAttribute("symbol", symbol); //$NON-NLS-1$
            node.setAttribute("ratio", String.valueOf(map.get(symbol))); //$NON-NLS-1$
            saveHistory(node, symbol);
            root.appendChild(node);
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = new File(Platform.getLocation().toFile(), "currencies.xml"); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();
    } catch (Exception e) {
        logger.error(e, e);
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static Element createElement(Document doc, Element root, String name, String text, String sortAttribute,
        String sortValue) {//from w w w  . ja va 2s.  c o m

    if (name == null) {
        throw new XMLToolException("Element name cannot be null!");
    } else if (name.trim().length() == 0) {
        throw new XMLToolException("Element name has to contain at least one character!");
    }

    Element elem = doc.createElement(name);
    if (text != null) {
        Text textNode = doc.createTextNode(StringUtil.getXMLSafeString(text));
        elem.appendChild(textNode);
    }

    if (sortAttribute == null || sortValue == null) {
        root.appendChild(elem);
    } else {
        Element[] childElems = getElements(root);
        if (childElems.length == 0) {
            root.appendChild(elem);
        } else {
            int i = 0;
            for (; i < childElems.length; i++) {
                String childValue = childElems[i].getAttribute(sortAttribute);
                if (childValue != null && childValue.compareToIgnoreCase(sortValue) >= 0) {
                    break;
                }
            }

            if (i < childElems.length) {
                root.insertBefore(elem, childElems[i]);
            } else {
                root.appendChild(elem);
            }
        }
    }

    return elem;
}

From source file:com.microsoft.windowsazure.messaging.Registration.java

/**
 * Appends the tags node to the registration xml
 * @param doc   The document to modify//from  w  ww  . j a  v a  2s  .  co  m
 * @param registrationDescription   The parent element
 */
protected void appendTagsNode(Document doc, Element registrationDescription) {
    List<String> tagList = getTags();
    if (tagList != null && tagList.size() > 0) {
        String tagsNodeValue = tagList.get(0);

        for (int i = 1; i < tagList.size(); i++) {
            tagsNodeValue += "," + tagList.get(i);
        }

        Element tags = doc.createElement("Tags");
        tags.appendChild(doc.createTextNode(tagsNodeValue));
        registrationDescription.appendChild(tags);
    }
}

From source file:ConfigFiles.java

public static void saveXML(boolean blank, String filename) {
    boolean saved = true;
    try {/*from  w w  w . j a va 2s. com*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        DOMSource source = new DOMSource(document);
        Comment simpleComment = document.createComment(
                "\n Master config file for TSC.\n \n Logs" + " Path: Where CE and PE write their getLogs()."
                        + " Reports Path: Where all reports are saved.\n "
                        + "Test Suite Config: All info about the current " + "Test Suite (Test Plan).\n");
        document.appendChild(simpleComment);
        Element root = document.createElement("Root");
        document.appendChild(root);
        Element rootElement = document.createElement("FileType");
        root.appendChild(rootElement);
        rootElement.appendChild(document.createTextNode("config"));
        try {
            addTag("CentralEnginePort", tceport.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("CentralEnginePort", "", root, blank, document);
        }
        //             try{addTag("ResourceAllocatorPort",traPort.getText(),root,blank,document);}
        //             catch(Exception e){addTag("ResourceAllocatorPort","",root,blank,document);}
        //             try{addTag("HttpServerPort",thttpPort.getText(),root,blank,document);}
        //             catch(Exception e){addTag("HttpServerPort","",root,blank,document);}
        try {
            addTag("TestCaseSourcePath", ttcpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("TestCaseSourcePath", "", root, blank, document);
        }
        try {
            addTag("LibsPath", libpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("LibsPath", "", root, blank, document);
        }
        try {
            addTag("UsersPath", tUsers.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("UsersPath", "", root, blank, document);
        }
        try {
            addTag("PredefinedSuitesPath", tSuites.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("PredefinedSuitesPath", "", root, blank, document);
        }

        try {
            addTag("ArchiveLogsPath", tsecondarylog.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("ArchiveLogsPath", "", root, blank, document);
        }
        try {
            addTag("ArchiveLogsPathActive", logsenabled.isSelected() + "", root, blank, document);
        } catch (Exception e) {
            addTag("ArchiveLogsPath", "", root, blank, document);
        }

        try {
            addTag("LogsPath", tlog.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("LogsPath", "", root, blank, document);
        }
        rootElement = document.createElement("LogFiles");
        root.appendChild(rootElement);
        try {
            addTag("logRunning", trunning.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logRunning", "", rootElement, blank, document);
        }
        try {
            addTag("logDebug", tdebug.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logDebug", "", rootElement, blank, document);
        }
        try {
            addTag("logSummary", tsummary.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logSummary", "", rootElement, blank, document);
        }
        try {
            addTag("logTest", tinfo.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logTest", "", rootElement, blank, document);
        }
        try {
            addTag("logCli", tcli.getText(), rootElement, blank, document);
        } catch (Exception e) {
            addTag("logCli", "", rootElement, blank, document);
        }
        try {
            addTag("DbConfigFile", tdbfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("DbConfigFile", "", root, blank, document);
        }
        try {
            addTag("EpNames", tepid.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("EpNames", "", root, blank, document);
        }
        try {
            addTag("EmailConfigFile", temailfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("EmailConfigFile", "", root, blank, document);
        }
        try {
            addTag("GlobalParams", tglobalsfile.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("GlobalParams", "", root, blank, document);
        }
        try {
            addTag("TestConfigPath", testconfigpath.getText(), root, blank, document);
        } catch (Exception e) {
            addTag("TestConfigPath", "", root, blank, document);
        }
        String temp;
        if (blank)
            temp = "fwmconfig";
        else
            temp = filename;
        File file = new File(RunnerRepository.temp + RunnerRepository.getBar() + "Twister"
                + RunnerRepository.getBar() + temp + ".xml");
        Result result = new StreamResult(file);
        transformer.transform(source, result);
        System.out.println("Saving to: " + RunnerRepository.USERHOME + "/twister/config/");
        FileInputStream in = new FileInputStream(file);
        RunnerRepository.uploadRemoteFile(RunnerRepository.USERHOME + "/twister/config/", in, file.getName());
    } catch (ParserConfigurationException e) {
        System.out
                .println("DocumentBuilder cannot be created which" + " satisfies the configuration requested");
        saved = false;
    } catch (TransformerConfigurationException e) {
        System.out.println("Could not create transformer");
        saved = false;
    } catch (Exception e) {
        e.printStackTrace();
        saved = false;
    }
    if (saved) {
        CustomDialog.showInfo(JOptionPane.INFORMATION_MESSAGE, RunnerRepository.window, "Successful",
                "File successfully saved");
    } else {
        CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, RunnerRepository.window.mainpanel.p4.getConfig(),
                "Warning", "File could not be saved ");
    }
}

From source file:fi.helsinki.lib.simplerest.RootCommunitiesResource.java

@Get("html|xhtml|xml")
public Representation toXml() {
    DomRepresentation representation = null;
    Document d = null;
    try {//  w w  w.  j  a  v  a2 s . c om
        representation = new DomRepresentation(MediaType.ALL);
        d = representation.getDocument();
    } catch (IOException ex) {
        log.log(Priority.INFO, ex, ex);
    }

    representation.setIndenting(true);

    Element html = d.createElement("html");
    d.appendChild(html);

    Element head = d.createElement("head");
    html.appendChild(head);

    Element title = d.createElement("title");
    head.appendChild(title);
    title.appendChild(d.createTextNode("Root communities"));

    Element body = d.createElement("body");
    html.appendChild(body);

    Element ul = d.createElement("ul");
    setId(ul, "rootcommunities");
    body.appendChild(ul);

    String url = "";
    try {
        url = getRequest().getResourceRef().getIdentifier();
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e, e);
    }
    url = url.substring(0, url.lastIndexOf('/') + 1);
    url += "community/";
    for (Community community : communities) {

        Element li = d.createElement("li");
        Element a = d.createElement("a");

        a.setAttribute("href", url + Integer.toString(community.getID()));
        a.appendChild(d.createTextNode(community.getName()));
        li.appendChild(a);
        ul.appendChild(li);
    }

    Element form = d.createElement("form");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("method", "post");
    makeInputRow(d, form, "name", "Name");
    makeInputRow(d, form, "short_description", "Short description");
    makeInputRow(d, form, "introductory_text", "Introductory text");
    makeInputRow(d, form, "copyright_text", "Copyright text");
    makeInputRow(d, form, "side_bar_text", "Side bar text");
    makeInputRow(d, form, "logo", "Logo", "file");

    Element submitButton = d.createElement("input");
    submitButton.setAttribute("type", "submit");
    submitButton.setAttribute("value", "Create a new root community.");

    form.appendChild(submitButton);
    body.appendChild(form);

    try {
        if (context != null) {
            context.abort();
        }
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e, e);
    }
    return representation;
}

From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java

private void createPomBuild(Document doc, Element rootElement) {
    Element build = doc.createElement("build");
    rootElement.appendChild(build);//from   ww w .ja  va  2 s.c  om
    Element plugins = doc.createElement("plugins");
    build.appendChild(plugins);

    Element plugin = doc.createElement("plugin");
    plugins.appendChild(plugin);
    createPomGroupArtifactVersion(doc, plugin, "org.apache.maven.plugins", "maven-compiler-plugin", "2.3.2");
    Element configuration = doc.createElement("configuration");
    plugin.appendChild(configuration);
    Element source = doc.createElement("source");
    source.appendChild(doc.createTextNode("1.6"));
    Element target = doc.createElement("target");
    target.appendChild(doc.createTextNode("1.6"));
    configuration.appendChild(source);
    configuration.appendChild(target);
}

From source file:com.idega.slide.util.WebdavLocalResource.java

@SuppressWarnings("deprecation")
private Enumeration<LocalResponse> propfindMethod(NodeRevisionDescriptor descriptor)
        throws HttpException, IOException {
    if (descriptor == null) {
        return null;
    }//from   w  w w .  j a  va2  s.  c  o  m

    if (properties != null) {
        return properties;
    }

    try {
        Vector<LocalResponse> responses = new Vector<LocalResponse>();
        LocalResponse response = new LocalResponse();
        response.setHref(getPath());
        responses.add(response);

        @SuppressWarnings("unchecked")
        List<NodeProperty> nodeProperties = Collections.list(descriptor.enumerateProperties());
        List<Property> properties = new ArrayList<Property>();
        for (NodeProperty p : nodeProperties) {
            String localName = p.getPropertyName().getName();
            Property property = null;

            if (localName.equals(RESOURCETYPE)) {
                Object oValue = p.getValue();
                String value = oValue == null ? null : oValue.toString();

                Element element = null;
                if ("<collection/>".equals(value)) {
                    element = getCollectionElement();
                } else if (CoreConstants.EMPTY.equals(value)) {
                    element = getEmptyElement();
                } else {
                    Document doc = XmlUtil.getDocumentBuilder().newDocument();
                    String namespace = p.getNamespace();
                    String tagName = p.getName();
                    element = doc.createElementNS(namespace, tagName);
                    element.appendChild(doc.createTextNode(value));
                }

                property = new ResourceTypeProperty(response, element);
            } else if (localName.equals(LOCKDISCOVERY)) {
                /*DocumentBuilderFactory factory =
                 DocumentBuilderFactory.newInstance();
                 factory.setNamespaceAware(true);
                 DocumentBuilder builder = factory.newDocumentBuilder();
                 Document doc = builder.newDocument();
                 Element element = doc.createElement("collection");
                 property = new LockDiscoveryProperty(response,element);*/
                throw new RuntimeException("LockDiscoveryProperty not yet implemented for: " + getPath());
            } else if (CREATIONDATE.equals(localName)) {
                setCreationDate((String) p.getValue());
            } else if (GETLASTMODIFIED.equals(localName)) {
                setGetLastModified((String) p.getValue());
            } else {
                LocalProperty lProperty = new LocalProperty(response);
                property = lProperty;
                lProperty.setName(p.getName());
                lProperty.setNamespaceURI(p.getNamespace());
                lProperty.setLocalName(p.getName());
                Object oValue = p.getValue();
                String value = oValue == null ? null : oValue.toString();
                lProperty.setPropertyAsString(value);
            }

            if (property != null) {
                properties.add(property);
            }
        }

        if (!ListUtil.isEmpty(properties)) {
            response.setProperties(new Vector<Property>(properties));
        }

        this.properties = responses.elements();
        if (this.properties != null) {
            setProperties(3, 0); //   Need to set basic properties
        }

        return this.properties;
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error getting properties for: " + getPath() + ": " + e.getMessage(), e);

        if (e instanceof ObjectNotFoundException) {
            getSlideAPI().deletetDefinitionFile(((ObjectNotFoundException) e).getObjectUri());

            HttpException he = new HttpException("Resource on path: " + getPath() + " not found");
            he.setReasonCode(WebdavStatus.SC_NOT_FOUND);
            throw he;
        } else if (e instanceof RevisionDescriptorNotFoundException) {
            getSlideAPI().deletetDefinitionFile(((RevisionDescriptorNotFoundException) e).getObjectUri());
        }

        return null;
    }
}

From source file:Exporters.SaveFileExporter.java

public Element getVulnAsElement(Vulnerability vuln, Document doc) {

    Base64 b64 = new Base64();

    Element vulnElement = doc.createElement("vuln");
    if (vuln.isIs_custom_risk() == false) {
        vulnElement.setAttribute("custom-risk", "false");
        vulnElement.setAttribute("cvss", vuln.getCvss_vector_string());
    } else {// w  ww. j ava 2s. c  o  m
        vulnElement.setAttribute("custom-risk", "true");
    }
    vulnElement.setAttribute("category", vuln.getRisk_category());
    vulnElement.setAttribute("risk-score", "" + vuln.getRiskScore());

    Element vulnTitle = doc.createElement("title");
    vulnTitle.appendChild(doc.createTextNode(b64.encodeAsString(vuln.getTitle().getBytes())));

    Element identifiersElement = doc.createElement("identifiers");
    HashMap identifiersMap = vuln.getIdentifiers();
    Iterator it = identifiersMap.keySet().iterator();
    while (it.hasNext()) {
        String hashed_title = (String) it.next();
        String import_tool = (String) identifiersMap.get(hashed_title);
        // add a tag mofo!
        Element identifier = doc.createElement("identifier");
        identifier.setAttribute("hash", hashed_title);
        identifier.setAttribute("import_tool", import_tool);
        identifiersElement.appendChild(identifier);
    }

    Element vulnDescription = doc.createElement("description");
    vulnDescription.appendChild(doc.createTextNode(b64.encodeAsString(vuln.getDescription().getBytes())));

    Element vulnRecommendation = doc.createElement("recommendation");
    vulnRecommendation.appendChild(doc.createTextNode(b64.encodeAsString(vuln.getRecommendation().getBytes())));

    //TODO Fill out <References> tag
    Element vulnReferences = doc.createElement("references");
    Enumeration refs_enums = vuln.getReferences().elements();
    while (refs_enums.hasMoreElements()) {
        Reference ref = (Reference) refs_enums.nextElement();
        Element vulnReference = doc.createElement("reference");
        vulnReference.setAttribute("description", ref.getDescription());
        vulnReference.appendChild(doc.createTextNode(ref.getUrl()));
        vulnReferences.appendChild(vulnReference);
    }

    Element affectedHosts = doc.createElement("affected-hosts");
    Enumeration enums = vuln.getAffectedHosts().elements();
    while (enums.hasMoreElements()) {
        Host host = (Host) enums.nextElement();

        // Create all the lovely element nodes
        Element affectedHost = doc.createElement("host");
        Element ipAddress = doc.createElement("ip-address");
        if (host.getIp_address() != null) {
            ipAddress.appendChild(doc.createTextNode(host.getIp_address()));
        }
        Element hostname = doc.createElement("hostname");
        if (host.getHostname() != null) {
            hostname.appendChild(doc.createTextNode(host.getHostname()));
        }
        Element netbios = doc.createElement("netbios-name");
        if (host.getNetbios_name() != null) {
            netbios.appendChild(doc.createTextNode(host.getNetbios_name()));
        }
        Element os = doc.createElement("operating-system");
        if (host.getOperating_system() != null) {
            os.appendChild(doc.createTextNode(host.getOperating_system()));
        }
        Element macAddress = doc.createElement("mac-address");
        if (host.getMac_address() != null) {
            macAddress.appendChild(doc.createTextNode(host.getMac_address()));
        }
        Element portnumber = doc.createElement("portnumber");
        if (host.getPortnumber() != null) {
            portnumber.appendChild(doc.createTextNode(host.getPortnumber()));
        }
        Element protocol = doc.createElement("protocol");
        if (host.getProtocol() != null) {
            protocol.appendChild(doc.createTextNode(host.getProtocol()));
        }

        Element note = doc.createElement("note");
        if (host.getNotes() != null) {
            Note n = host.getNotes();
            note.appendChild(doc.createTextNode(b64.encodeAsString(n.getNote_text().getBytes())));
        }

        // Append them to the affected Host node
        affectedHost.appendChild(ipAddress);
        affectedHost.appendChild(hostname);
        affectedHost.appendChild(netbios);
        affectedHost.appendChild(os);
        affectedHost.appendChild(macAddress);
        affectedHost.appendChild(portnumber);
        affectedHost.appendChild(protocol);
        affectedHost.appendChild(note);

        // Add that host to the affected hosts node
        affectedHosts.appendChild(affectedHost);
    }

    vulnElement.appendChild(vulnTitle);
    vulnElement.appendChild(identifiersElement);
    vulnElement.appendChild(vulnDescription);
    vulnElement.appendChild(vulnRecommendation);
    vulnElement.appendChild(vulnReferences);
    vulnElement.appendChild(affectedHosts);
    return vulnElement;
}