/** * This is the preferred way for creating a Representation via a customized Resource serialization * * @param rootName * @param serialization */ public JdomRepresentation(String rootName, CoupleList<String, Object> serialization) { Element root = new Element(rootName); for (Couple<String, Object> couple : serialization) { Element elt = new Element(couple.getLeft()); if (couple.getRight() == null) { elt.setText(this.getEmptyValue()); } else { elt.setText(couple.getRight().toString()); } root.addContent(elt); } this.document = new Document(root); }
private synchronized void doConfigClearspace() throws UnauthorizedException { Log.debug("Starting Clearspace configuration."); List<String> bindInterfaces = getServerInterfaces(); if (bindInterfaces.size() == 0) { // We aren't up and running enough to tell Clearspace what interfaces to bind to. Log.debug("No bind interfaces found to config Clearspace"); throw new IllegalStateException("There are no binding interfaces."); } try { XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo(); String path = IM_URL_PREFIX + "configureComponent/"; // Creates the XML with the data Document groupDoc = DocumentHelper.createDocument(); Element rootE = groupDoc.addElement("configureComponent"); Element domainE = rootE.addElement("domain"); domainE.setText(serverInfo.getXMPPDomain()); for (String bindInterface : bindInterfaces) { Element hostsE = rootE.addElement("hosts"); hostsE.setText(bindInterface); } Element portE = rootE.addElement("port"); portE.setText(String.valueOf(ExternalComponentManager.getServicePort())); Log.debug( "Trying to configure Clearspace with: Domain: " + serverInfo.getXMPPDomain() + ", hosts: " + bindInterfaces.toString() + ", port: " + port); executeRequest(POST, path, rootE.asXML()); // Done, Clearspace was configured correctly, clear the task Log.debug("Clearspace was configured, stopping the task."); TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask); configClearspaceTask = null; } catch (UnauthorizedException ue) { throw ue; } catch (Exception e) { // It is not supported exception, wrap it into an UnsupportedOperationException throw new UnsupportedOperationException("Unexpected error", e); } }
public Document serialize(Object object, Document doc) { Class c = object.getClass(); Integer id = getID(object); map.put(object, id); String mapSize = Integer.toString(map.size()); // creating serialization objects Element objectElement = new Element("object"); objectElement.setAttribute(new Attribute("class", c.getName())); objectElement.setAttribute(new Attribute("id", mapSize)); doc.getRootElement().addContent(objectElement); if (!c.isArray()) // class is not an array { Field[] fields = c.getDeclaredFields(); ArrayList<Element> fieldXML = serializeFields(fields, object, doc); for (int i = 0; i < fieldXML.size(); i++) { objectElement.addContent(fieldXML.get(i)); } } else // class is an array { Object array = object; objectElement.setAttribute(new Attribute("length", Integer.toString(Array.getLength(array)))); if (c.getComponentType().isPrimitive()) // class is array of primitives { for (int i = 0; i < Array.getLength(array); i++) { Element value = new Element("value"); value.setText(Array.get(c, i).toString()); objectElement.addContent(value); } } else // class is array of references { for (int j = 0; j < Array.getLength(array); j++) { Element ref = new Element("reference"); id = getID(Array.get(c, j)); if (id != -1) { ref.setText(Integer.toString(id)); } } for (int k = 0; k < Array.getLength(array); k++) { serialize(Array.get(array, k), doc); } } } if (currentElement == 0) { referenceID = 0; } return doc; }
private static Element parseElement(XMLStreamReader xsr) throws XMLStreamException { // xsr points to a START_ELEMENT event. Create the element and read all its attributes // Then read all its children events Element element = new Element(xsr.getLocalName()); // text that will be added to the element. Text can come in different events, so we add it here // and add it to the element at the end StringBuilder elementText = new StringBuilder(); int attributeCount = xsr.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { element.putAttribute(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i)); } while (xsr.hasNext()) { xsr.next(); if (xsr.getEventType() == XMLStreamConstants.END_ELEMENT) { // element is closed. Move the cursor and return it // check if there is some text to add before (empty text is not added, but added text is not // trimmed) // we set empty text also if the element has no children if (!elementText.toString().trim().isEmpty() || !element.hasChildren()) { element.setText(elementText.toString()); } // xsr.next(); return element; } else if (xsr.getEventType() == XMLStreamConstants.CHARACTERS) { // an attribute of the current element elementText.append(xsr.getText()); } else if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) { // new element begins -> read it recursively and add it to the current element element.addChild(parseElement(xsr)); } } // we reached the end of the document without the tag end -> error parsing throw new XMLStreamException( "End of the document unexpectedly reached. Element " + element.getName() + " not closed"); }
/** Establece el sub-elemento Source */ private void setSource() { Element eAux; eAux = new Element("Source"); // eAux.setAttribute("Type","pcap o xml"); eAux.setText(getPBExport().getExpSource()); addContent(eAux); }
/** {@inheritDoc } */ @Override public JdomRepresentation add(String nodeName, String nodeValue) throws XmlException { Element element = new Element(nodeName, this.document.getRootElement().getNamespace()); element.setText(nodeValue); this.document.getRootElement().addContent(element); return this; }
public String createTable() { Element root = new Element("table"); root.setAttribute("border", "0"); Document doc = new Document(root); Element thead = new Element("thead"); Element th = new Element("th"); th.addContent("A header"); th.setAttribute("class", "aka_header_border"); thead.addContent(th); Element th2 = new Element("th"); th2.addContent("Another header"); th2.setAttribute("class", "aka_header_border"); thead.addContent(th2); root.addContent(thead); Element tr1 = new Element("tr"); Element td1 = new Element("td"); td1.setAttribute("valign", "top"); td1.setAttribute("class", "cellBorders"); td1.setText("cell contents"); tr1.addContent(td1); root.addContent(tr1); XMLOutputter outp = new XMLOutputter(); Format format = Format.getPrettyFormat(); format.setOmitDeclaration(true); outp.setFormat(format); Writer writer = new StringWriter(); try { outp.output(doc, writer); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } return writer.toString(); }
/** * 普通版填写包的公共部分 * @param root 开始节点 * @param map 参数map * @param sCycName 循环节点名 * @return */ public Element writeptPublicNode(Element root,HashMap map,String sCycName) { Element node=null; try { String sName=""; String sValue=""; List list=root.getChildren(); for(int i=0;i<list.size();i++) { node=(Element)list.get(i); sName=node.getName(); sName=sName.trim(); sValue=(String)map.get(sName); //System.err.println("sName:"+sName+":"+sValue); if(sCycName.equals(sName)&&(root.getName()).trim().equals("ReqParamSet")) { //System.err.println("find cyc node:"+sName ); return node; } else if(sValue!=null && !"".equals(sValue) ) node.setText(sValue); node=writeptPublicNode(node,map,sCycName); } }catch(Exception ex) { ex.printStackTrace(); System.err.println("error:"+ex.getMessage()); } return node; }
/** {@inheritDoc } */ @Override public JdomRepresentation set(String nodeName, String value) { try { Element elt = getElement(nodeName); elt.setText(value); } catch (XmlException ex) { add(nodeName, value); } return this; }
@Override public void literal(final String name, final String value) { if (name.isEmpty()) { element.setText(value); } else if (name.startsWith(ATTRIBUTE_MARKER)) { element.addAttribute(name.substring(1), value); } else { element.createChild(name).setText(value); } }
// TODO : to be tested ! @Override public JdomRepresentation addAll(String nodeName, String listName, List<Object> values) { Element list = new Element(listName); for (Object o : values) { Element e = new Element(nodeName); e.setText(o.toString()); list.addContent(e); } this.document.getRootElement().addContent(list); return this; }
// public static void write(OutputStream stream, Element element, int hashLength) throws // XMLStreamException { // XMLOutputFactory xof = XMLOutputFactory.newInstance(); // IndentingXMLStreamWriter xtw = new // IndentingXMLStreamWriter(xof.createXMLStreamWriter(stream)); // writeXMLStreamWriter(xtw, element, hashLength); // } // private static void writeXMLStreamWriter(XMLStreamWriter xtw, Element element, int hashLength) throws XMLStreamException { if (hashLength > 0) { String hash = element.getHash(hashLength); Element hashElement = new Element(CRC_ELEMENT); hashElement.setText(hash); element.addChild(hashElement); } writeElement(xtw, element); xtw.writeEndDocument(); xtw.flush(); xtw.close(); if (hashLength > 0) { element.removeChildren(CRC_ELEMENT); } }
/** * * @param map 需要写入的参数map * @param start 开始节点 * @param bNew 是否新增节点再写入参数 * @return */ public void writeParaMap(Element start,HashMap map) { try { String sName=""; String sValue=""; Element node=null; List list=start.getChildren(); for(int i=0;i<list.size();i++) { node=(Element)list.get(i); sName=node.getName(); sName=sName.trim(); sValue=(String)map.get(sName); if(sValue!=null && !"".equals(sValue) ); node.setText(sValue); } }catch(Exception ex) { ex.printStackTrace(); System.err.println("error:"+ex.getMessage()); } return ; }
/** * sauvegarde une course dans un fichier xml temporaire listcourses.xml * * @param pcourse est l'objet course recuperée depuis l'ihm */ public static void saveCoursesinTempFile(EssaiOrCourse pcourse) { SAXBuilder sxb = new SAXBuilder(); Document document; try { document = sxb.build(new File(xmlTempPathListCourses)); Element racine = document.getRootElement(); // racine.removeChildren("course"); Element newCourseElement = new Element("course"); newCourseElement.setAttribute( "nomEssaiOrCourse", pcourse.getNomEssaiOrCourse_() != null ? pcourse.getNomEssaiOrCourse_() : ""); newCourseElement.setAttribute( "typeEssaiOrCourse", pcourse.getTypeEssaiOrCourse_() != null ? pcourse.getTypeEssaiOrCourse_().toString() : ""); Element departAutomatique = new Element("departAutomatique"); Element typeDeFin = new Element("typeDeFin"); Element heureDebut = new Element("heureDebut"); Element heureFin = new Element("heureFin"); Element nbToursMax = new Element("nbToursMax"); Element dureeMaxPilotage = new Element("dureeMaxPilotage"); Element dureeConsecutiveMaxPilotage = new Element("dureeConsecutiveMaxPilotage"); Element commentaire = new Element("commentaire"); departAutomatique.setText(pcourse.isDepartAutomatique_() ? "true" : "false"); typeDeFin.setText(pcourse.getTypeDeFin_() != null ? pcourse.getTypeDeFin_().toString() : ""); heureDebut.setText( pcourse.getHeureDebut_() != null ? pcourse.getHeureDebut_().toString() : ""); heureFin.setText(pcourse.getHeureFin_() != null ? pcourse.getHeureFin_().toString() : ""); nbToursMax.setText( pcourse.getNbToursMax_() >= 0 ? String.valueOf(pcourse.getNbToursMax_()) : ""); dureeMaxPilotage.setText( pcourse.getDureeMaxPilotage_() >= 0 ? String.valueOf(pcourse.getDureeMaxPilotage_()) : ""); dureeConsecutiveMaxPilotage.setText( pcourse.getDureeConsecutiveMaxPilotage_() >= 0 ? String.valueOf(pcourse.getDureeConsecutiveMaxPilotage_()) : ""); commentaire.setText(pcourse.getCommentaire_() != null ? pcourse.getCommentaire_() : ""); newCourseElement.addContent(departAutomatique); newCourseElement.addContent(typeDeFin); newCourseElement.addContent(heureDebut); newCourseElement.addContent(heureFin); newCourseElement.addContent(nbToursMax); newCourseElement.addContent(dureeMaxPilotage); newCourseElement.addContent(dureeConsecutiveMaxPilotage); newCourseElement.addContent(commentaire); racine.addContent(newCourseElement); enregistre(document, xmlTempPathListCourses); } catch (Exception e) { e.getMessage(); } }
protected void text(String text) { String existing = current.getText(); current.setText(existing != null ? existing + text : text); }
public static void guardarArchivoXML(ListaPartida listaDePartidas, boolean valor) { Ficha nodoAuxiliarPote; Ficha nodoAuxiliarUsuario; Ficha nodoAuxiliarServidor; Partida partidaActual; Ficha fichaActual; /* Se crea una raiz de la estructura */ Element root = new Element("fichas"); /* Es posible agregar atributos a la estructura inicial */ root.setAttribute("tipo", "lista de fichas"); Iterator iteradorPartida = listaDePartidas.getIterator(); Iterator iteradorFichaUsuario; Iterator iteradorFichaPote; Iterator iteradorFichaServidor; Element ID; Element fichaPote; Element fichaUsuario; Element fichaServidor; Element fichaX; Element fichaY; while (iteradorPartida.hasNext()) { ID = new Element("ID"); fichaPote = new Element("fichapote"); fichaUsuario = new Element("fichausuario"); fichaServidor = new Element("fichaservidor"); partidaActual = (Partida) iteradorPartida.next(); ID.setAttribute("id", Integer.toString(partidaActual.getID())); iteradorFichaPote = partidaActual.getFichapote().getIterator(); while (iteradorFichaPote.hasNext()) { fichaX = new Element("X"); fichaY = new Element("Y"); fichaActual = (Ficha) iteradorFichaPote.next(); fichaX.setText(Integer.toString(fichaActual.getX())); fichaY.setText(Integer.toString(fichaActual.getY())); fichaPote.addContent(fichaX); fichaPote.addContent(fichaY); } ID.addContent(fichaPote); iteradorFichaUsuario = partidaActual.getFichausuario().getIterator(); while (iteradorFichaUsuario.hasNext()) { fichaX = new Element("X"); fichaY = new Element("Y"); fichaActual = (Ficha) iteradorFichaUsuario.next(); fichaX.setText(Integer.toString(fichaActual.getX())); fichaY.setText(Integer.toString(fichaActual.getY())); fichaUsuario.addContent(fichaX); fichaUsuario.addContent(fichaY); } ID.addContent(fichaUsuario); iteradorFichaServidor = partidaActual.getFichaservidor().getIterator(); while (iteradorFichaServidor.hasNext()) { fichaX = new Element("X"); fichaY = new Element("Y"); fichaActual = (Ficha) iteradorFichaServidor.next(); fichaX.setText(Integer.toString(fichaActual.getX())); fichaY.setText(Integer.toString(fichaActual.getY())); fichaServidor.addContent(fichaX); fichaServidor.addContent(fichaY); } ID.addContent(fichaServidor); root.addContent(ID); } /* Se crea un documento nuevo */ Document doc = new Document(root); try { /* Se genera un flujo de salida de datos XML */ XMLOutputter out = new XMLOutputter(); /* Se asocia el flujo de salida con el archivo donde se guardaran los datos */ FileOutputStream file = new FileOutputStream(nombreArchivoFicha); /* Se manda el documento generado hacia el archivo XML */ out.output(doc, file); /* Se limpia el buffer ocupado por el objeto file y se manda a cerrar el archivo */ file.flush(); file.close(); /* En este caso se manda a imprimir el archivo por la consola */ /* ESTE PROCESO NO ES OBLIGATORIO PARA PROCESAR EL XML */ out.output(doc, System.out); } catch (Exception e) { e.printStackTrace(); } }
void transform() throws JDOMException, IOException { // EXMARaLDAs "transformer class" - true für 2.0 StylesheetFactory ssf = new StylesheetFactory(true); try { // the first transformation, resulting in a String... String firstCMDI = ssf.applyExternalStylesheetToExternalXMLFile(xsltFile, comaFile); // ...from which we build a Document SAXBuilder builder = new SAXBuilder(); StringReader in = new StringReader(firstCMDI); cmdi = builder.build(in); // set the namespace Namespace ns = Namespace.getNamespace("clarin", "http://www.clarin.eu/cmd/"); // Replace variable CORPUS_NAME // in Header (MdSelfLink, ResourceRef), HZSKCorpusMetadata (Name, ID)) XPath xURLs = XPath.newInstance("//clarin:MdSelfLink | //clarin:ResourceRef"); xURLs.addNamespace(ns); List allURLs = xURLs.selectNodes(cmdi); String[] splitFile = comaFile.split("\\\\"); String comaFileName = splitFile[splitFile.length - 1].replace(".coma", ""); for (Object o : allURLs) { Element url = (Element) o; String selfLink = url.getText(); url.setText(selfLink.replace("CORPUS_NAME", comaFileName)); } // Replace language codes with names // in XPath xLanguageNames = XPath.newInstance(""); xLanguageNames.addNamespace(ns); List allLanguageNames = xLanguageNames.selectNodes(cmdi); for (Object o : allLanguageNames) { Element languageName = (Element) o; languageName.setText(ISOLanguageCodeHelper.getLanguageName(languageName.getText())); } // Replace language names with codes // in DocumentationLanguages XPath xLanguageCodes = XPath.newInstance("//clarin:DocumentationLanguages/descendant::clarin:iso-639-3-code"); xLanguageCodes.addNamespace(ns); List allLanguageCodes = xLanguageCodes.selectNodes(cmdi); for (Object o : allLanguageCodes) { Element languageCode = (Element) o; languageCode.setText(ISOLanguageCodeHelper.getLanguageCode(languageCode.getText())); } // Resources // add value of mimetype attribute to resourceType elements XPath xResourceTypes = XPath.newInstance("//clarin:ResourceType"); xResourceTypes.addNamespace(ns); List allResourceTypes = xResourceTypes.selectNodes(cmdi); for (Object o : allResourceTypes) { Element resourceType = (Element) o; FileNameMap fileNameMap = URLConnection.getFileNameMap(); String filename = resourceType.getAttributeValue("mimetype").toLowerCase(); String mimetype = fileNameMap.getContentTypeFor(filename); if (mimetype != null) { resourceType.setAttribute("mimetype", mimetype); } else if (filename.endsWith("exb") || filename.endsWith("exs")) { resourceType.setAttribute("mimetype", "text/xml"); } else { resourceType.setAttribute("mimetype", "unknown"); } } // Language // hzsk-corpus-materials // file size for the Size-elements XPath xMediaFiles = XPath.newInstance("//clarin:hzsk-corpus-materials/descendant::clarin:MediaFile"); xMediaFiles.addNamespace(ns); List allFiles = xMediaFiles.selectNodes(cmdi); for (Object o : allFiles) { Element mediafile = (Element) o; File asocFile = new File(mediafile.getChild("ResourceLink", ns).getText()); // es wird jetzt nicht sehr genau, aber das taugt... Element size = mediafile.getChild("Size", ns); size.addContent(String.valueOf(asocFile.length())); } // write CMDI-file Writer fileWriter = new FileWriter(cmdiFile); XMLOutputter serializer = new XMLOutputter(); serializer.output(cmdi, fileWriter); } catch (SAXException ex) { Logger.getLogger(Coma2CMDI.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Coma2CMDI.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(Coma2CMDI.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(Coma2CMDI.class.getName()).log(Level.SEVERE, null, ex); } }
@SuppressWarnings({"deprecation", "unused"}) public static Document builderOpensearchResponeDocument( List<Geochannelmetadata> geochannelmetadataList) { Document document = DocumentHelper.createDocument(); Element root = document.addElement("kml", "http://www.opengis.net/kml/2.2"); // 创建根节点 root.addNamespace("geoww", "http://www.geoww.net/geochannel"); root.addNamespace("geofeed", "http://www.geoww.net/geofeed"); root.addNamespace("opensearch", "http://a9.com/-/spec/opensearch/1.1/"); root.addNamespace("geo", "http://a9.com/-/opensearch/extensions/geo/1.0/"); root.addNamespace("time", "http://a9.com/-/opensearch/extensions/time/1.0/"); root.addComment("This is a test for opensearch respone!"); Element geowwGeoChannelSearch = root.addElement("geoww:GeoChannelSearch"); Element opensearchtotalResults = geowwGeoChannelSearch.addElement("opensearch:totalResults"); Element opensearchstartIndex = geowwGeoChannelSearch.addElement("opensearch:startIndex"); Element opensearchitemsPerPage = geowwGeoChannelSearch.addElement("opensearch:itemsPerPage"); Element opensearchQuery = geowwGeoChannelSearch.addElement("opensearch:Query"); Element geowwSearchLinks = geowwGeoChannelSearch.addElement("geoww:SearchLinks"); for (Geochannelmetadata geochannelmetadata : geochannelmetadataList) { Element geowwGeoChannel = geowwGeoChannelSearch.addElement("geoww:GeoChannel"); // geoww:GeoChannel Element name = geowwGeoChannel.addElement("name"); Element description = geowwGeoChannel.addElement("description"); Element geowwMetadata = geowwGeoChannel.addElement("geoww:Metadata"); Element geofeedAccessFeed = geowwGeoChannel.addElement("geofeed:AccessFeed"); // geoww:Metadata Element geowwtitle = geowwMetadata.addElement("geoww:title"); Element Geometry = geowwMetadata.addElement("Geometry"); Element geowwsMetadataList = geowwMetadata.addElement("geoww:MetadataList"); // geoww:MetadataList//geoww:GeowwURI Element geowwGeowwURI = geowwsMetadataList.addElement("geoww:GeowwURI"); Element geowwnote = geowwGeowwURI.addElement("geoww:note"); Element geowwgeowwURI = geowwGeowwURI.addElement("geoww:geowwURI"); if (null != geochannelmetadata.getGeowwUri()) { geowwgeowwURI.setText(geochannelmetadata.getGeowwUri()); } // // geoww:MetadataList//Data // Title Element titleData = geowwsMetadataList.addElement("Data"); titleData.addAttribute("name", "Title"); Element titleValue = titleData.addElement("value"); if (null != geochannelmetadata.getTitle()) { titleValue.setText(geochannelmetadata.getTitle()); } // alternativeTitle Element alternativeTitleData = geowwsMetadataList.addElement("Data"); alternativeTitleData.addAttribute("name", "AlternativeTitle"); Element alternativeTitleValue = alternativeTitleData.addElement("value"); if (null != geochannelmetadata.getAlternativeTitle()) { alternativeTitleValue.setText(geochannelmetadata.getAlternativeTitle()); } // ServiceLanguage Element serviceLanguageData = geowwsMetadataList.addElement("Data"); serviceLanguageData.addAttribute("name", "ServiceLanguage"); Element serviceLanguageValue = serviceLanguageData.addElement("value"); if (null != geochannelmetadata.getServiceLanguage()) { serviceLanguageValue.setText(geochannelmetadata.getServiceLanguage()); } // Abstract Element abstractData = geowwsMetadataList.addElement("Data"); abstractData.addAttribute("name", "Abstract"); Element abstractValue = abstractData.addElement("value"); if (null != geochannelmetadata.getAbstract_()) { abstractValue.setText(geochannelmetadata.getAbstract_()); } // TopicCategory Element topicCategoryData = geowwsMetadataList.addElement("Data"); topicCategoryData.addAttribute("name", "TopicCategory"); Element topicCategoryValue = topicCategoryData.addElement("value"); if (null != geochannelmetadata.getTopicCategory()) { topicCategoryValue.setText(geochannelmetadata.getTopicCategory()); } // GeoChannelIdentifier Element geoChannelIdentifierData = geowwsMetadataList.addElement("Data"); geoChannelIdentifierData.addAttribute("name", "GeoChannelIdentifier"); Element geoChannelIdentifierValue = geoChannelIdentifierData.addElement("value"); if (null != geochannelmetadata.getGeoChannelIdentifier()) { geoChannelIdentifierValue.setText(geochannelmetadata.getGeoChannelIdentifier()); } // ResourceIdentifiers Element resourceIdentifiersData = geowwsMetadataList.addElement("Data"); resourceIdentifiersData.addAttribute("name", "ResourceIdentifiers"); Element resourceIdentifiersValue = resourceIdentifiersData.addElement("value"); if (null != geochannelmetadata.getResourceIdentifiers()) { resourceIdentifiersValue.setText(geochannelmetadata.getResourceIdentifiers()); } // Keyword Element keywordData = geowwsMetadataList.addElement("Data"); keywordData.addAttribute("name", "Keyword"); Element keywordValue = keywordData.addElement("value"); if (null != geochannelmetadata.getKeyword()) { keywordValue.setText(geochannelmetadata.getKeyword()); } // ResourceType Element resourceTypeData = geowwsMetadataList.addElement("Data"); resourceTypeData.addAttribute("name", "ResourceType"); Element resourceTypeValue = resourceTypeData.addElement("value"); if (null != geochannelmetadata.getResourceType()) { resourceTypeValue.setText(geochannelmetadata.getResourceType()); } // SpatialFeature Element SpatialFeatureData = geowwsMetadataList.addElement("Data"); SpatialFeatureData.addAttribute("name", "SpatialFeature"); Element SpatialFeatureValue = SpatialFeatureData.addElement("value"); if (null != geochannelmetadata.getSpatialFeature()) { SpatialFeatureValue.setText(geochannelmetadata.getSpatialFeature()); } // SpatialMetrics Element SpatialMetricsData = geowwsMetadataList.addElement("Data"); SpatialMetricsData.addAttribute("name", "SpatialMetrics"); Element SpatialMetricsValue = SpatialMetricsData.addElement("value"); if (null != geochannelmetadata.getSpatialMetrics()) { SpatialMetricsValue.setText(geochannelmetadata.getSpatialMetrics().toString()); } // BoundingBox Element BoundingBoxData = geowwsMetadataList.addElement("Data"); BoundingBoxData.addAttribute("name", "BoundingBox"); Element BoundingBoxValue = BoundingBoxData.addElement("value"); if (null != geochannelmetadata.getBoundingBox()) { BoundingBoxValue.setText(geochannelmetadata.getBoundingBox()); } // SpatialExtent Element SpatialExtentData = geowwsMetadataList.addElement("Data"); SpatialExtentData.addAttribute("name", "SpatialExtent"); Element SpatialExtentValue = SpatialExtentData.addElement("value"); if (null != geochannelmetadata.getSpatialExtent()) { SpatialExtentValue.setText(geochannelmetadata.getSpatialExtent()); } // VerticalExtentLow Element verticalExtentLowData = geowwsMetadataList.addElement("Data"); verticalExtentLowData.addAttribute("name", "VerticalExtentLow"); Element verticalExtentLowValue = verticalExtentLowData.addElement("value"); if (null != geochannelmetadata.getVerticalExtentLow()) { verticalExtentLowValue.setText(geochannelmetadata.getVerticalExtentLow().toString()); } // VerticalExtentHigh Element verticalExtentHighData = geowwsMetadataList.addElement("Data"); verticalExtentHighData.addAttribute("name", "VerticalExtentHigh"); Element verticalExtentHighValue = verticalExtentHighData.addElement("value"); if (null != geochannelmetadata.getVerticalExtentHigh()) { verticalExtentHighValue.setText(geochannelmetadata.getVerticalExtentHigh().toString()); } // SpatialReferenceSystem Element SpatialReferenceSystemData = geowwsMetadataList.addElement("Data"); SpatialReferenceSystemData.addAttribute("name", "SpatialReferenceSystem"); Element SpatialReferenceSystemValue = SpatialReferenceSystemData.addElement("value"); if (null != geochannelmetadata.getSpatialReferenceSystem()) { SpatialReferenceSystemValue.setText(geochannelmetadata.getSpatialReferenceSystem()); } // SpatialResolution Element SpatialResolutionData = geowwsMetadataList.addElement("Data"); SpatialResolutionData.addAttribute("name", "SpatialResolution"); Element SpatialResolutionValue = SpatialResolutionData.addElement("value"); if (null != geochannelmetadata.getSpatialResolution()) { SpatialResolutionValue.setText(geochannelmetadata.getSpatialResolution().toString()); } // TemporalExtentStart Element TemporalExtentStartData = geowwsMetadataList.addElement("Data"); TemporalExtentStartData.addAttribute("name", "TemporalExtentStart"); Element TemporalExtentStartValue = TemporalExtentStartData.addElement("value"); if (null != geochannelmetadata.getTemporalExtentStart()) { TemporalExtentStartValue.setText(geochannelmetadata.getTemporalExtentStart().toGMTString()); } // TemporalExtentEnd Element TemporalExtentEndData = geowwsMetadataList.addElement("Data"); TemporalExtentEndData.addAttribute("name", "TemporalExtentEnd"); Element TemporalExtentEndValue = TemporalExtentEndData.addElement("value"); if (null != geochannelmetadata.getTemporalExtentEnd()) { TemporalExtentEndValue.setText(geochannelmetadata.getTemporalExtentEnd().toGMTString()); } // PublicationDate Element PublicationDateData = geowwsMetadataList.addElement("Data"); PublicationDateData.addAttribute("name", "PublicationDate"); Element PublicationDateValue = PublicationDateData.addElement("value"); if (null != geochannelmetadata.getPublicationDate()) { PublicationDateValue.setText(geochannelmetadata.getPublicationDate().toGMTString()); } // DataFormat Element DataFormatData = geowwsMetadataList.addElement("Data"); DataFormatData.addAttribute("name", "DataFormat"); Element DataFormatValue = DataFormatData.addElement("value"); if (null != geochannelmetadata.getDataFormat()) { DataFormatValue.setText(geochannelmetadata.getDataFormat()); } // ResponsibleOrganisation Element ResponsibleOrganisationData = geowwsMetadataList.addElement("Data"); ResponsibleOrganisationData.addAttribute("name", "ResponsibleOrganisation"); Element ResponsibleOrganisationValue = ResponsibleOrganisationData.addElement("value"); if (null != geochannelmetadata.getResponsibleOrganisation()) { ResponsibleOrganisationValue.setText(geochannelmetadata.getResponsibleOrganisation()); } // FrequencyOfUpdata Element FrequencyOfUpdataData = geowwsMetadataList.addElement("Data"); FrequencyOfUpdataData.addAttribute("name", "FrequencyOfUpdata"); Element FrequencyOfUpdataValue = FrequencyOfUpdataData.addElement("value"); if (null != geochannelmetadata.getFrequencyOfUpdata()) { FrequencyOfUpdataValue.setText(geochannelmetadata.getFrequencyOfUpdata()); } // LimitationOnPublicAccess Element LimitationOnPublicAccessData = geowwsMetadataList.addElement("Data"); LimitationOnPublicAccessData.addAttribute("name", "LimitationOnPublicAccess"); Element LimitationOnPublicAccessValue = LimitationOnPublicAccessData.addElement("value"); if (null != geochannelmetadata.getLimitationOnPublicAccess()) { LimitationOnPublicAccessValue.setText(geochannelmetadata.getLimitationOnPublicAccess()); } // UseConstraints Element UseConstraintsData = geowwsMetadataList.addElement("Data"); UseConstraintsData.addAttribute("name", "UseConstraints"); Element UseConstraintsValue = UseConstraintsData.addElement("value"); if (null != geochannelmetadata.getUseConstraints()) { UseConstraintsValue.setText(geochannelmetadata.getUseConstraints()); } // CoupledGeoChannels Element CoupledGeoChannelsData = geowwsMetadataList.addElement("Data"); CoupledGeoChannelsData.addAttribute("name", "CoupledGeoChannels"); Element CoupledGeoChannelsValue = CoupledGeoChannelsData.addElement("value"); if (null != geochannelmetadata.getCoupledGeoChannels()) { CoupledGeoChannelsValue.setText(geochannelmetadata.getCoupledGeoChannels()); } // AdditionalInformation Element AdditionalInformationData = geowwsMetadataList.addElement("Data"); AdditionalInformationData.addAttribute("name", "AdditionalInformation"); Element AdditionalInformationValue = AdditionalInformationData.addElement("value"); if (null != geochannelmetadata.getAdditionalInformation()) { AdditionalInformationValue.setText(geochannelmetadata.getAdditionalInformation()); } // MetadataDateTime Element MetadataDateTimeData = geowwsMetadataList.addElement("Data"); MetadataDateTimeData.addAttribute("name", "MetadataDateTime"); Element MetadataDateTimeValue = MetadataDateTimeData.addElement("value"); if (null != geochannelmetadata.getMetadataDateTime()) { MetadataDateTimeValue.setText(geochannelmetadata.getMetadataDateTime().toGMTString()); } // MetadataLanguage Element MetadataLanguageData = geowwsMetadataList.addElement("Data"); MetadataLanguageData.addAttribute("name", "MetadataLanguage"); Element MetadataLanguageValue = MetadataLanguageData.addElement("value"); if (null != geochannelmetadata.getMetadataLanguage()) { MetadataLanguageValue.setText(geochannelmetadata.getMetadataLanguage()); } // MetadataContact Element MetadataContactData = geowwsMetadataList.addElement("Data"); MetadataContactData.addAttribute("name", "MetadataContact"); Element MetadataContactValue = MetadataContactData.addElement("value"); if (geochannelmetadata.getMetadataContact() != null) { MetadataContactValue.setText(geochannelmetadata.getMetadataContact()); } } return document; }
/** * Método public static void guardarArchivoXML(ListaUsuarios listaDeUsuarios): Este método permite * guardar la lista de usuarios en un archivo XML. El procesamiento se hace con jdom */ public static void guardarArchivoXML(ListaUsuario listaDeUsuarios) { Usuario nodoAuxiliar; /* Se crea una raiz de la estructura */ Element root = new Element("usuarios"); /* Es posible agregar atributos a la estructura inicial */ root.setAttribute("tipo", "lista de usuarios"); Iterator iterador = listaDeUsuarios.getIterator(); while (iterador.hasNext()) { /* Se crea la etiqueta "usuario" */ Element usuarios = new Element("usuario"); nodoAuxiliar = (Usuario) iterador.next(); /* Se crean las etiquetas nombre, apellido y cargo */ Element nick = new Element("nick"); Element clave = new Element("clave"); Element nombre = new Element("nombre"); Element apellido = new Element("apellido"); Element fechanac = new Element("fechanac"); Element avatar = new Element("avatar"); /* Se inicializa cada etiqueta con sus valores de la lista */ nick.setText(nodoAuxiliar.getNickname()); clave.setText(nodoAuxiliar.getClave()); nombre.setText(nodoAuxiliar.getNombre()); apellido.setText(nodoAuxiliar.getApellido()); fechanac.setText(nodoAuxiliar.getFechanaci()); avatar.setText(nodoAuxiliar.getAvatar()); /* Se añaden las etiquetas a la etiqueta principal (usuario) */ /* estableciendo que un usuario tiene nombre, apellido y cargo */ usuarios.addContent(nick); usuarios.addContent(clave); usuarios.addContent(nombre); usuarios.addContent(apellido); usuarios.addContent(fechanac); usuarios.addContent(avatar); /* Se añade el nuevo usuario a la estructura XML */ root.addContent(usuarios); } /* Se crea un documento nuevo */ Document doc = new Document(root); try { /* Se genera un flujo de salida de datos XML */ XMLOutputter out = new XMLOutputter(); /* Se asocia el flujo de salida con el archivo donde se guardaran los datos */ FileOutputStream file = new FileOutputStream(nombreArchivo); /* Se manda el documento generado hacia el archivo XML */ out.output(doc, file); /* Se limpia el buffer ocupado por el objeto file y se manda a cerrar el archivo */ file.flush(); file.close(); /* En este caso se manda a imprimir el archivo por la consola */ /* ESTE PROCESO NO ES OBLIGATORIO PARA PROCESAR EL XML */ out.output(doc, System.out); } catch (Exception e) { e.printStackTrace(); } }
//改写XML文件的某一元素的值 //strRoute为XML文件从根元素开始到该元素的父元素的路径 //strElement为需要读取的元素 //flag为当XML含有多个同名元素时,需要改写元素所处的序号 public void write(String strRoute, String strElement, String strSet, int flag) { //SAXBuilder builder=new SAXBuilder(); try { String str = null; Document doc = builder.build(xmlFileName); Element root = doc.getRootElement(); Element element = root; StringTokenizer st = new StringTokenizer(strRoute, ":"); str = st.nextToken(); while (st.hasMoreTokens()) { str = st.nextToken(); //mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str); element = element.getChild(str); } // mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"test :"+str); element = (Element) element.getParent(); //若需要改写的不是XML文件的第一个同名元素,则获取该元素 //方法为:将之前的元素依次移到后面,需要改写的元素前移至第一个 /* * if(flag>1) { int j=flag; while(j!=1) { * * Element tmp=element.getChild(str); * element.addContent(tmp.detach()); j--; } } */ element = element.getChild(str).getChild(strElement); // mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"gettxt // "+element.getText()); element.setText(strSet); //若需要改写的不是XML文件的第一个同名元素 //上面改变了次序,需要在成功改写后恢复原有次序 /* * if(flag!=1) { * * java.util.List children=element.getChildren(); Iterator * iterator=children.iterator(); int count=0; * while(iterator.hasNext()) { Element * child=(Element)iterator.next(); count++; } * * System.out.println("count"+count); * * k=(count+1-flag)%count; * * while(k!=0) { Element tmp=element.getChild(str); * element.addContent(tmp.detach()); k--; } } * */ XMLOutputter outputter = new XMLOutputter("", false, "GB2312"); PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(xmlFileName))); Document myDocument = root.getDocument(); outputter.output(myDocument, out); out.close(); } catch (JDOMException jdome) { jdome.printStackTrace(); // mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName // + " is not well-formed\n"); } catch (IOException ioe) { ioe.printStackTrace(); // mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe); } catch (Exception e) { e.printStackTrace(); // mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, // "write not succeed\n"); } }
public Element nextToken() throws HTMLReaderException { Node node = null; current = null; try { while ((node = lr.nextNode()) != null) { String html = node.toHtml(true).trim(); if (html.length() != 0) { current = new Element(); if (html.startsWith("</")) { current.setType(Element.Type.End); current.setText(html); } else if (html.startsWith("<")) { current.setType(Element.Type.Start); int i = html.indexOf(' '); if (i != -1) { StringBuffer id = new StringBuffer(); StringBuffer value = new StringBuffer(); boolean idSeek = true; boolean valueSeek = false; current.setText(html.substring(1, i)); html = html.substring(i + 1); if (html.endsWith("/>")) { html = html.substring(0, html.length() - 2); current.setOpen(false); } else html = html.substring(0, html.length() - 1); html = html.trim(); for (i = 0; i < html.length(); i++) { char ch = html.charAt(i); if (valueSeek) { if (ch == '"') { current.addAttribute(id.toString(), value.toString()); idSeek = true; valueSeek = false; id.setLength(0); value.setLength(0); } else value.append(ch); } else if (ch == '=') { idSeek = false; } else if (ch == '"') { valueSeek = true; } else id.append(ch); } } else current.setText(html); } else { current.setType(Element.Type.Text); current.setText(html); } return current; } } } catch (ParserException ex) { throw new HTMLReaderException(ex.toString()); } return null; }