Gerar Xml

5 respostas
C

Olá pessoal!

Eu fiz essa classe abaixo para gerar Xml, porém ela apenas aparece no console, como faço para salvar .xml e se existe uma forma mais fácil de gerar Xml...

/*
 * GerarXml.java
 *
 * Created on 5 de Outubro de 2006, 14:10
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package xml;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;


/**
 *
 * @author ccarvalho
 */
public class GerarXml {
    
    public static void main(String[] args) {
     
    try {
      // Find the implementation
      DocumentBuilderFactory factory 
       = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      DocumentBuilder builder = factory.newDocumentBuilder();
      DOMImplementation impl = builder.getDOMImplementation();
      
      // Create the document
      DocumentType svgDOCTYPE = impl.createDocumentType(
       "svg", "-//W3C//DTD SVG 1.0//EN", 
       "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"
      );
      Document doc = impl.createDocument(
       "http://www.w3.org/2000/svg", "svg", svgDOCTYPE);
       
      // Fill the document
      Node rootElement = doc.getDocumentElement();
      ProcessingInstruction xmlstylesheet 
       = doc.createProcessingInstruction("xml-stylesheet",
       "type=\"text/css\" href=\"standard.css\"");
      Comment comment = doc.createComment(
       "An example from Chapter 10 of Processing XML with Java");
      doc.insertBefore(comment, rootElement);
      doc.insertBefore(xmlstylesheet, rootElement);
      
      Node desc = doc.createElementNS(
       "http://www.w3.org/2000/svg", "desc");
      rootElement.appendChild(desc);
      Text descText = doc.createTextNode(
       "An example from Processing XML with Java");     
      desc.appendChild(descText);
      
      Node nome = doc.createElementNS(
       "http://www.w3.org/2000/svg", "nome");
      rootElement.appendChild(nome);
      Text nomeText = doc.createTextNode(
       "Christielen");     
      nome.appendChild(nomeText);
      
      // Serialize the document onto System.out
      TransformerFactory xformFactory 
       = TransformerFactory.newInstance();  
      Transformer idTransform = xformFactory.newTransformer();
      Source input = new DOMSource(doc);
      Result output = new StreamResult(System.out);
      idTransform.transform(input, output);

    }
    catch (FactoryConfigurationError e) { 
      System.out.println("Could not locate a JAXP factory class"); 
    }
    catch (ParserConfigurationException e) { 
      System.out.println(
        "Could not locate a JAXP DocumentBuilder class"
      ); 
    }
    catch (DOMException e) {
      System.err.println(e); 
    }
    catch (TransformerConfigurationException e) {
      System.err.println(e); 
    }
    catch (TransformerException e) {
      System.err.println(e); 
    }
  
  }
    
}

5 Respostas

G

XStream é magavilhoso :grin:

XStream xstream = new XStream(new DomDriver());

xstream.alias("person", Person.class);
xstream.alias("phonenumber", PhoneNumber.class);

Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));

String xml = xstream.toXML(joe);

Resultado:

<person>
  <firstname>Joe</firstname>
  <lastname>Walnes</lastname>
  <phone>
    <code>123</code>
    <number>1234-456</number>
  </phone>
  <fax>
    <code>123</code>
    <number>9999-999</number>
  </fax>
</person>

http://xstream.codehaus.org/

E

XStream uso e recomendo :grin:

C

Olá Guilherme

Para user o:

xstream.useAttributeFor("author", Author.class);

A classe Author pode ter mais de uma atributo, pois eu fiz com vários e ele
só mapeou o primeiro atributos.

Como posso fazer??? Isso é possível???

C

Alguém sabe salvar esse arquivo Java usando XStream “.xml”??

J

Dando uma olhada rápida no código, parece que você está usando o JDom… Se for, é fácil salvar o xml em um arquivo:

XMLOutputter xout = new XMLOutputter("  ", true);
xout.output(doc, System.out);

Mais info, veja aqui: http://www.javafree.org/javabb/viewtopic.jbb?t=847694

Criado 5 de outubro de 2006
Ultima resposta 8 de out. de 2006
Respostas 5
Participantes 4