Jump to content

Transformar um ficheiro XML numa string em Java


Pontus
 Share

Recommended Posts

Como é que estás a ler o conteúdo do XML? E queres ler os dados do XML ou ler o conteúdo incluído as tags?

Se queres ler apenas o conteúdo, depende se estás a usar DOM ou SAX, se queres ler todo o conteúdo incluindo as tags, basta leres o ficheiro como uma stream de leitura de caracteres, por exemplo usando um FileReader.

Link to comment
Share on other sites

File file = new File ("filepath");

FileReader fileread = new FileReader(file);

BufferedReader bufread = new BufferedReader(fileread)

//String str = new String();

StringBuilder sb = new StringBuilder();

sb.append(bufread);

return sb.toString();

assim?

Link to comment
Share on other sites

Bem acabei por fazer de outra maneira:

public static String XmlToString() throws ParserConfigurationException, TransformerConfigurationException,

            SAXException, IOException, TransformerException {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.parse("/home/ateixeira/zbr.xml");

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        //inicializar StreamResult para gravar para String

        StreamResult result = new StreamResult(new StringWriter());

        DOMSource source = new DOMSource(doc);

        transformer.transform(source, result);

        String xmlString = result.getWriter().toString();

        System.out.println(xmlString);

        //devolver a string

        return xmlString;

    }

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.