List of usage examples for org.dom4j Document addElement
Element addElement(String name);
Element
node with the given name to this branch and returns a reference to the new node. From source file:nidonuevo.model.Engine.java
private void saveGameToXML() { Document document = DocumentHelper.createDocument(); Element root = document.addElement("Game"); //General//from www . ja v a 2s.c om Element general = root.addElement("General"); general.addElement("title").addText(title); general.addElement("width").addText("" + getWidth()); general.addElement("height").addText("" + getHeight()); //Mapas Element maps = root.addElement("Maps"); for (int i = 0; i < LMS.getMaps().size(); i++) { Element map = maps.addElement("Map").addAttribute("id", "" + i); map.addElement("NumberLayers").addText("" + LMS.getMaps().get(i).getLayers().size()); Element source = map.addElement("Source"); for (int j = 0; j < LMS.getMaps().get(i).getLayers().size(); j++) { source.addElement("Path").addAttribute("id", "" + j).addText(LMS.getMaps().get(i).getPaths()[j]); source.addElement("Img").addAttribute("id", "" + j).addText(LMS.getMaps().get(i).getDirImg()[j]); //falta width,gehith, layer. mapa, etc, terminar mapash } //TRIGGERS Element triggers = map.addElement("Triggers"); for (int j = 0; j < LMS.getMaps().get(i).getTriggers().size(); j++) { Element trigger = triggers.addElement("Trigger"); if (LMS.getMaps().get(i).getTriggers().get(j) instanceof TriggerChangeMap) { TriggerChangeMap aux = (TriggerChangeMap) LMS.getMaps().get(i).getTriggers().get(j); trigger.addElement("type").addText("TriggerChangeMap"); trigger.addElement("par").addText("" + aux.x); trigger.addElement("par").addText("" + aux.y); trigger.addElement("par").addText("" + aux.getChangeTo()); trigger.addElement("par").addText("" + aux.getpX()); trigger.addElement("par").addText("" + aux.getpY()); } else if (LMS.getMaps().get(i).getTriggers().get(j) instanceof TriggerMap) { TriggerMap aux = (TriggerMap) LMS.getMaps().get(i).getTriggers().get(j); trigger.addElement("type").addText("TriggerMap"); trigger.addElement("par").addText("" + aux.x); trigger.addElement("par").addText("" + aux.y); trigger.addElement("par").addText("" + aux.getChangeTo()); trigger.addElement("par").addText("" + aux.getpX()); trigger.addElement("par").addText("" + aux.getpY()); } else if (LMS.getMaps().get(i).getTriggers().get(j) instanceof TriggerMini) { TriggerMini aux = (TriggerMini) LMS.getMaps().get(i).getTriggers().get(j); trigger.addElement("type").addText("TriggerMini"); trigger.addElement("par").addText("" + aux.x); trigger.addElement("par").addText("" + aux.y); trigger.addElement("par").addText("" + aux.getChangeTo()); } else if (LMS.getMaps().get(i).getTriggers().get(j) instanceof TriggerMonologue) { TriggerMonologue aux = (TriggerMonologue) LMS.getMaps().get(i).getTriggers().get(j); trigger.addElement("type").addText("TriggerMonologue"); trigger.addElement("par").addText("" + aux.x); trigger.addElement("par").addText("" + aux.y); trigger.addElement("par").addText("" + aux.getChangeTo()); } } //GOALS Element goals = map.addElement("Goals"); for (int j = 0; j < LMS.getMaps().get(i).getGoals().size(); j++) { Element goal = goals.addElement("Goal"); Goal aux = LMS.getMaps().get(i).getGoals().get(j); //int id, boolean active,String desc,int tipo goal.addElement("id").addText("" + aux.getId()); goal.addElement("active").addText("" + aux.isActive()); goal.addElement("description").addText("" + aux.getDescription()); goal.addElement("type").addText("" + aux.getTipo()); } //MINIGAME } //Player Element player = root.addElement("Player"); player.addElement("positionX").addText("" + LMS.getPlayer().getPositionX()); player.addElement("positionY").addText("" + LMS.getPlayer().getPositionY()); player.addElement("dir").addText("" + LMS.getPlayer().getDir()); player.addElement("path").addText("" + LMS.getPlayer().getPath()); player.addElement("contDelay").addText("" + LMS.getPlayer().getContDelay()); player.addElement("width").addText("" + LMS.getPlayer().getWidth()); player.addElement("height").addText("" + LMS.getPlayer().getHeight()); player.addElement("tW").addText("" + LMS.getPlayer().gettW()); player.addElement("tH").addText("" + LMS.getPlayer().gettH()); player.addElement("speed").addText("" + LMS.getPlayer().getSpeed()); player.addElement("happiness").addText("" + LMS.getPlayer().getHappiness()); player.addElement("numberOfFriends").addText("" + LMS.getPlayer().getNumberOfFriends()); player.addElement("numberOfTrophies").addText("" + LMS.getPlayer().getNumberOfTrophies()); Element inventory = player.addElement("Inventory"); for (int i = 0; i < LMS.getPlayer().getInventory().getItems().size(); i++) { Element item = inventory.addElement("Item").addAttribute("id", "" + LMS.getPlayer().getInventory().getItems().get(i).getId()); item.addElement("name").addText("" + LMS.getPlayer().getInventory().getItems().get(i).getName()); item.addElement("stock").addText("" + LMS.getPlayer().getInventory().getItems().get(i).getStock()); item.addElement("description") .addText("" + LMS.getPlayer().getInventory().getItems().get(i).getDescription()); item.addElement("image").addText("" + LMS.getPlayer().getInventory().getItems().get(i).getImage()); } //MINIJUEGOS Element miniGames = root.addElement("MiniGames"); for (int j = 0; j < LMS.getPlayer().getMiniGames().size(); j++) { Element miniGame = miniGames.addElement("MiniGame"); miniGame.addElement("id").addText("" + j); MiniGame aux = LMS.getPlayer().getMiniGames().get(j); //jugadores Element persons = miniGame.addElement("Persons"); ; for (int k = 0; k < aux.getPersons().size(); k++) { persons.addElement("id").addText("" + aux.getPersons().get(k).id); } //mensajes Element messages = miniGame.addElement("Messages"); for (int k = 0; k < aux.getMessages().size(); k++) { messages.addElement("message").addText("" + aux.getMessages().get(k)); } //respuestas Element answers = miniGame.addElement("Answers"); for (int k = 0; k < aux.getAnswers().size(); k++) { String auxS = ""; for (int j1 = 0; j1 < aux.getAnswers().get(k).length; j1++) { if (j1 == 0) { auxS = aux.getAnswers().get(k)[j1]; } else { auxS = auxS + "-" + aux.getAnswers().get(k)[j1]; } } answers.addElement("answer").addText(auxS); } //respuestas correctas Element correct = miniGame.addElement("Correct1"); for (int k = 0; k < aux.getCorrect().size(); k++) { correct.addElement("correct").addText("" + aux.getCorrect().get(k)); } //puntos Element points = miniGame.addElement("Points"); for (int k = 0; k < aux.getPoints().size(); k++) { points.addElement("point").addText("" + aux.getPoints().get(k)); } } //FIN //WRITER try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndent(true); XMLWriter writer = new XMLWriter(new FileWriter("juego.xml"), format); writer.write(document); writer.setIndentLevel(2); writer.close(); } catch (IOException ex) { Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:nl.knaw.dans.dccd.model.EntityTree.java
License:Apache License
/** Get the dom4j xml document object that represents the entity tree, * but then only the structure, not the Entity objects. * * @return The document/*from w ww .j a va 2 s. c om*/ */ public Document getTreeStructAsDocument() { // note: if projectEntity == null, throw an exception ? // if (getProjectEntity() == null) { logger.warn("No project, creating empty tree"); } // create a XML DOM document using dom4j // don't delegate to the entities this time Document document = DocumentHelper.createDocument(); Element structmap = document.addElement(ENTITYTREESTRUCT_NS_PREFIX + ENTITYTREESTRUCT_NS);//("structmap"); // root structmap.addAttribute("version", ENTITYTREESTRUCT_VERSION); structmap.addNamespace(ENTITYTREESTRUCT_NS, ENTITYTREESTRUCT_NS_URL); buildTreeStructElementTree(structmap, getProjectEntity()); return document; }
From source file:nl.ru.cmbi.vase.parse.VASEXMLParser.java
License:Apache License
public static void write(VASEDataObject data, OutputStream xmlOut) throws IOException { DocumentFactory df = DocumentFactory.getInstance(); Document doc = df.createDocument(); Element root = doc.addElement("xml"); if (data.getTitle() != null) { Element title = root.addElement("title"); title.setText(data.getTitle());//w w w.j a va 2 s .c o m } Element fasta = root.addElement("fasta"); ByteArrayOutputStream fastaStream = new ByteArrayOutputStream(); FastaParser.toFasta(data.getAlignment().getMap(), fastaStream); fasta.add(df.createCDATA(new String(fastaStream.toByteArray(), StandardCharsets.UTF_8))); Element pdb = root.addElement("pdb"); pdb.addAttribute("pdbid", data.getPdbID()); table2xml(data.getTable(), root); if (data.getPlots().size() > 0) { Element plots = root.addElement("plots"); for (PlotDescription pd : data.getPlots()) { Element plot = plots.addElement("plot"); plot.addElement("x").setText(pd.getXAxisColumnID()); plot.addElement("y").setText(pd.getYAxisColumnID()); plot.addAttribute("title", pd.getPlotTitle()); } } XMLWriter writer = new XMLWriter(xmlOut); writer.write(doc); writer.close(); }
From source file:no.ntnu.idi.freerider.xml.RequestSerializer.java
License:Apache License
/** Serialize this Request. */ public static String serialize(Request request) { if (request == null) return null; //Create and initialize the request's major structure. Document xmldocument = DocumentFactory.getInstance().createDocument(); xmldocument.setXMLEncoding(ProtocolConstants.PREFERRED_CHARSET.displayName()); //Possible alternative: try ISO-8859-1 Element root = xmldocument.addElement(ProtocolConstants.REQUEST); Element header = root.addElement(ProtocolConstants.REQUEST_HEADER); header.addAttribute(ProtocolConstants.REQUEST_TYPE_ATTRIBUTE, request.getType().toString()); header.addAttribute(ProtocolConstants.PROTOCOL_VERSION_ATTRIBUTE, ProtocolConstants.PROTOCOL_VERSION); header.addAttribute(ProtocolConstants.PROTOCOL_ATTRIBUTE, ProtocolConstants.PROTOCOL); Element data = root.addElement(ProtocolConstants.DATA); //Add data unique to this request. header.addAttribute(ProtocolConstants.USER_ATTRIBUTE, request.getUser().getID()); if (request instanceof RouteRequest) { data.add(SerializerUtils.serializeRoute(((RouteRequest) request).getRoute())); } else if (request instanceof SearchRequest) { SearchRequest req = (SearchRequest) request; data.add(SerializerUtils.serializeSearch(req.getStartPoint(), req.getEndPoint(), req.getStartTime(), req.getNumDays()));/* w w w. j a va2 s. c om*/ } else if (request instanceof UserRequest) { data.add(SerializerUtils.serializeUser(request.getUser())); } else if (request instanceof JourneyRequest) { data.add(SerializerUtils.serializeJourney(((JourneyRequest) request).getJourney())); } else if (request instanceof NotificationRequest) { data.add(SerializerUtils.serializeNotification(((NotificationRequest) request).getNotification())); } else if (request instanceof LoginRequest) { Element token = new DefaultElement(ProtocolConstants.ACCESS_TOKEN_ELEMENT); token.setText(((LoginRequest) request).getAccessToken()); data.add(token); } else if (request instanceof PreferenceRequest) { data.add(SerializerUtils.serializePreference(((PreferenceRequest) request).getPreference())); } else if (request instanceof CarRequest) { data.add(SerializerUtils.serializeCar(((CarRequest) request).getCar())); } else if (request instanceof SingleJourneyRequest) { data.addAttribute(ProtocolConstants.SINGLE_JOURNEY_ID, Integer.toString(((SingleJourneyRequest) request).getJourneySerial())); } return xmldocument.asXML(); }
From source file:no.ntnu.idi.freerider.xml.ResponseSerializer.java
License:Apache License
public static String serialize(Response responseObject) { //Initialize empty Response document. Document xmlResponse = DocumentFactory.getInstance().createDocument(); xmlResponse.setXMLEncoding(ProtocolConstants.PREFERRED_CHARSET.displayName()); //Possible alternative: try ISO-8859-1 Element responseRoot = xmlResponse.addElement(ProtocolConstants.RESPONSE); Element responseHeader = responseRoot.addElement(ProtocolConstants.RESPONSE_HEADER); responseHeader.addAttribute(ProtocolConstants.PROTOCOL_ATTRIBUTE, ProtocolConstants.PROTOCOL); // responseHeader.addAttribute("xmlns:tns", ProtocolConstants.XMLNS_RESPONSE); // responseHeader.addAttribute("xmlns:xsi", ProtocolConstants.XMLNS_XSI); // responseHeader.addAttribute("xsi:schemalocation", ProtocolConstants.XSI_SCHEMALOCATION_RESPONSE); responseHeader.addAttribute(ProtocolConstants.PROTOCOL_VERSION_ATTRIBUTE, ProtocolConstants.PROTOCOL_VERSION); //Handle null request errors. if (responseObject == null) { responseHeader.addAttribute(ProtocolConstants.RESPONSE_STATUS_ATTRIBUTE, ResponseStatus.FAILED.toString()); return xmlResponse.asXML(); }//from www .ja va 2s . c om //Complete initialization. responseHeader.addAttribute(ProtocolConstants.REQUEST_TYPE_ATTRIBUTE, responseObject.getType().toString()); if (responseObject.getErrorMessage() != null) { responseHeader.addAttribute(ProtocolConstants.ERROR_MESSAGE_ATTRIBUTE, responseObject.getErrorMessage()); } Element responseData = responseRoot.addElement(ProtocolConstants.DATA); //Add header data. responseHeader.addAttribute(ProtocolConstants.RESPONSE_STATUS_ATTRIBUTE, responseObject.getStatus().toString()); //Insert other data. if (responseObject instanceof JourneyResponse && ((JourneyResponse) responseObject).getJourneys() != null) { for (Journey journey : ((JourneyResponse) responseObject).getJourneys()) { Element journeyElement = SerializerUtils.serializeJourney(journey); if (journeyElement != null) { responseData.add(journeyElement); } } } if (responseObject instanceof RouteResponse && ((RouteResponse) responseObject).getRoutes() != null) { for (Route route : ((RouteResponse) responseObject).getRoutes()) { Element routeElement = SerializerUtils.serializeRoute(route); if (routeElement != null) { responseData.add(routeElement); } } } if (responseObject instanceof NotificationResponse && ((NotificationResponse) responseObject).getNotifications() != null) for (Notification note : ((NotificationResponse) responseObject).getNotifications()) { Element noteElement = SerializerUtils.serializeNotification(note); if (noteElement != null) responseData.add(noteElement); } if (responseObject instanceof PreferenceResponse && ((PreferenceResponse) responseObject).getPreferences() != null) { Element prefElement = SerializerUtils .serializePreference(((PreferenceResponse) responseObject).getPreferences()); if (prefElement != null) { responseData.add(prefElement); } } if (responseObject instanceof CarResponse && ((CarResponse) responseObject).getCar() != null) { Element carElement = SerializerUtils.serializeCar(((CarResponse) responseObject).getCar()); if (carElement != null) { responseData.add(carElement); } } if (responseObject instanceof UserResponse && ((UserResponse) responseObject).getUser() != null) { Element userElement = SerializerUtils.serializeUser(((UserResponse) responseObject).getUser()); if (userElement != null) { responseData.add(userElement); } } return xmlResponse.asXML(); }
From source file:org.alfresco.web.bean.dashboard.PageConfig.java
License:Open Source License
/** * Convert this config to an XML definition which can be serialized. * Example:// www . j a v a 2 s. c o m * <code> * <?xml version="1.0"?> * <dashboard> * <page id="main" layout-id="narrow-left-2column"> * <column> * <dashlet idref="clock" /> * <dashlet idref="random-joke" /> * </column> * <column> * <dashlet idref="getting-started" /> * <dashlet idref="task-list" /> * <dashlet idref="my-checkedout-docs" /> * <dashlet idref="my-documents" /> * </column> * </page> * </dashboard> * </code> * * @return XML for this config */ public String toXML() { try { Document doc = DocumentHelper.createDocument(); Element root = doc.addElement(ELEMENT_DASHBOARD); for (Page page : pages) { Element pageElement = root.addElement(ELEMENT_PAGE); pageElement.addAttribute(ATTR_ID, page.getId()); pageElement.addAttribute(ATTR_LAYOUTID, page.getLayoutDefinition().Id); for (Column column : page.getColumns()) { Element columnElement = pageElement.addElement(ELEMENT_COLUMN); for (DashletDefinition dashletDef : column.getDashlets()) { columnElement.addElement(ELEMENT_DASHLET).addAttribute(ATTR_REFID, dashletDef.Id); } } } StringWriter out = new StringWriter(512); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); writer.setWriter(out); writer.write(doc); return out.toString(); } catch (Throwable err) { throw new AlfrescoRuntimeException( "Unable to serialize Dashboard PageConfig to XML: " + err.getMessage(), err); } }
From source file:org.alfresco.web.bean.search.SearchContext.java
License:Open Source License
/** * @return this SearchContext as XML/*from w w w .j a va 2 s. c om*/ * * Example: * <code> * <?xml version="1.0" encoding="UTF-8"?> * <search> * <text>CDATA</text> * <mode>int</mode> * <location>XPath</location> * <categories> * <category>XPath</category> * </categories> * <content-type>String</content-type> * <folder-type>String</folder-type> * <mimetype>String</mimetype> * <attributes> * <attribute name="String">String</attribute> * </attributes> * <ranges> * <range name="String"> * <lower>String</lower> * <upper>String</upper> * <inclusive>boolean</inclusive> * </range> * </ranges> * <fixed-values> * <value name="String">String</value> * </fixed-values> * <query>CDATA</query> * </search> * </code> */ public String toXML() { try { NamespaceService ns = Repository.getServiceRegistry(FacesContext.getCurrentInstance()) .getNamespaceService(); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement(ELEMENT_SEARCH); root.addElement(ELEMENT_TEXT).addCDATA(this.text); root.addElement(ELEMENT_MODE).addText(Integer.toString(this.mode)); if (this.location != null) { root.addElement(ELEMENT_LOCATION).addText(this.location); } Element categories = root.addElement(ELEMENT_CATEGORIES); for (String path : this.categories) { categories.addElement(ELEMENT_CATEGORY).addText(path); } if (this.contentType != null) { root.addElement(ELEMENT_CONTENT_TYPE).addText(this.contentType); } if (this.folderType != null) { root.addElement(ELEMENT_FOLDER_TYPE).addText(this.folderType); } if (this.mimeType != null && this.mimeType.length() != 0) { root.addElement(ELEMENT_MIMETYPE).addText(this.mimeType); } Element attributes = root.addElement(ELEMENT_ATTRIBUTES); for (QName attrName : this.queryAttributes.keySet()) { attributes.addElement(ELEMENT_ATTRIBUTE).addAttribute(ELEMENT_NAME, attrName.toPrefixString(ns)) .addCDATA(this.queryAttributes.get(attrName)); } Element ranges = root.addElement(ELEMENT_RANGES); for (QName rangeName : this.rangeAttributes.keySet()) { RangeProperties rangeProps = this.rangeAttributes.get(rangeName); Element range = ranges.addElement(ELEMENT_RANGE); range.addAttribute(ELEMENT_NAME, rangeName.toPrefixString(ns)); range.addElement(ELEMENT_LOWER).addText(rangeProps.lower); range.addElement(ELEMENT_UPPER).addText(rangeProps.upper); range.addElement(ELEMENT_INCLUSIVE).addText(Boolean.toString(rangeProps.inclusive)); } Element values = root.addElement(ELEMENT_FIXED_VALUES); for (QName valueName : this.queryFixedValues.keySet()) { values.addElement(ELEMENT_VALUE).addAttribute(ELEMENT_NAME, valueName.toPrefixString(ns)) .addCDATA(this.queryFixedValues.get(valueName)); } // outputing the full lucene query may be useful for some situations Element query = root.addElement(ELEMENT_QUERY); String queryString = buildQuery(0); if (queryString != null) { query.addCDATA(queryString); } StringWriter out = new StringWriter(1024); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); writer.setWriter(out); writer.write(doc); return out.toString(); } catch (Throwable err) { throw new AlfrescoRuntimeException("Failed to export SearchContext to XML.", err); } }
From source file:org.apache.ddlutils.task.DumpMetadataTask.java
License:Apache License
/** * {@inheritDoc}// ww w .j ava2s .co m */ public void execute() throws BuildException { if (_dataSource == null) { log("No data source specified, so there is nothing to do.", Project.MSG_INFO); return; } Connection connection = null; try { Document document = DocumentFactory.getInstance().createDocument(); Element root = document.addElement("metadata"); root.addAttribute("driverClassName", _dataSource.getDriverClassName()); connection = _dataSource.getConnection(); dumpMetaData(root, connection.getMetaData()); OutputFormat outputFormat = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = null; outputFormat.setEncoding(_outputEncoding); if (_outputFile == null) { xmlWriter = new XMLWriter(System.out, outputFormat); } else { xmlWriter = new XMLWriter(new FileOutputStream(_outputFile), outputFormat); } xmlWriter.write(document); xmlWriter.close(); } catch (Exception ex) { throw new BuildException(ex); } finally { if (connection != null) { try { connection.close(); } catch (SQLException ex) { } } } }
From source file:org.apache.directory.studio.connection.core.io.ConnectionIO.java
License:Apache License
/** * Saves the connections using the writer. * * @param connections the connections//from ww w. ja v a 2 s . c o m * @param stream the OutputStream * @throws IOException if an I/O error occurs */ public static void save(Set<ConnectionParameter> connections, OutputStream stream) throws IOException { // Creating the Document Document document = DocumentHelper.createDocument(); // Creating the root element Element root = document.addElement(CONNECTIONS_TAG); if (connections != null) { for (ConnectionParameter connection : connections) { addConnection(root, connection); } } // Writing the file to disk OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding("UTF-8"); //$NON-NLS-1$ XMLWriter writer = new XMLWriter(stream, outformat); writer.write(document); writer.flush(); }
From source file:org.apache.directory.studio.connection.core.io.ConnectionIO.java
License:Apache License
/** * Saves the connection folders using the writer. * * @param connectionFolders the connection folders * @param stream the OutputStream// ww w. j a v a 2s. c o m * @throws IOException if an I/O error occurs */ public static void saveConnectionFolders(Set<ConnectionFolder> connectionFolders, OutputStream stream) throws IOException { // Creating the Document Document document = DocumentHelper.createDocument(); // Creating the root element Element root = document.addElement(CONNECTION_FOLDERS_TAG); if (connectionFolders != null) { for (ConnectionFolder connectionFolder : connectionFolders) { addFolderConnection(root, connectionFolder); } } // Writing the file to disk OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setEncoding("UTF-8"); //$NON-NLS-1$ XMLWriter writer = new XMLWriter(stream, outformat); writer.write(document); writer.flush(); }