1. Home
  2. Java XML Tutorial
  3. How to Convert String to XML in Java ?
Nguyễn Tuấn 1 năm trước

How to Convert String to XML in Java ?

Bài viết này sharecs trình bày cách convert String to XML và convert XML to String trong Java, sử dụng DOM parser và JDOM2 parser.

Convert String to XML ( DOM Parser )

Ví dụ dưới đây sẽ cho các bạn thấy cách convert String to XML java và ngược lại.

package com.sharecs.xml.tips;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

// DOM Parser
public class ConvertStringToXmlDom {

    final static String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<company>\n" +
            "    <staff id=\"1001\">\n" +
            "        <name>sharecs</name>\n" +
            "        <role>support</role>\n" +
            "        <salary currency=\"USD\">5000</salary>\n" +
            "        <!-- for special characters like < &, need CDATA -->\n" +
            "        <bio><![CDATA[HTML tag <code>testing</code>]]></bio>\n" +
            "    </staff>\n" +
            "    <staff id=\"1002\">\n" +
            "        <name>yflow</name>\n" +
            "        <role>admin</role>\n" +
            "        <salary currency=\"EUR\">8000</salary>\n" +
            "        <bio><![CDATA[a & b]]></bio>\n" +
            "    </staff>\n" +
            "</company>";

    public static void main(String[] args) {

        // String to XML Document
        Document document = convertStringToXml(str);

        // XML Document to String
        String xml = convertXmlToString(document);

        System.out.println(xml);

    }

    private static String convertXmlToString(Document doc) {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = null;
        try {
            transformer = tf.newTransformer();
            transformer.transform(domSource, result);
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
        return writer.toString();
    }

    private static Document convertStringToXml(String xmlString) {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            // optional, but recommended
            // process XML securely, avoid attacks like XML External Entities (XXE)
            dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

            DocumentBuilder builder = dbf.newDocumentBuilder();

            Document doc = builder.parse(new InputSource(new StringReader(xmlString)));

            return doc;

        } catch (ParserConfigurationException | IOException | SAXException e) {
            throw new RuntimeException(e);
        }

    }

}
<?xml version="1.0" encoding="utf-8" standalone="no"?><company>
    <staff id="1001">
        <name>sharecs</name>
        <role>support</role>
        <salary currency="USD">5000</salary>
        <!-- for special characters like < &, need CDATA -->
        <bio><![CDATA[HTML tag <code>testing</code>]]></bio>
    </staff>
    <staff id="1002">
        <name>yflow</name>
        <role>admin</role>
        <salary currency="EUR">8000</salary>
        <bio><![CDATA[a & b]]></bio>
    </staff>
</company>

Convert String to XML (JDOM2 Parser)

Vis dụ 2 chúng ta sẽ sử dụng JDOM2 parser.

  <dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
  </dependency>
package com.sharecs.xml.tips;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import javax.xml.XMLConstants;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

// JDOM2 Parser
public class ConvertStringToXmlJDom2 {

    final static String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<company>\n" +
            "    <staff id=\"1001\">\n" +
            "        <name>sharecs</name>\n" +
            "        <role>support</role>\n" +
            "        <salary currency=\"USD\">5000</salary>\n" +
            "        <!-- for special characters like < &, need CDATA -->\n" +
            "        <bio><![CDATA[HTML tag <code>testing</code>]]></bio>\n" +
            "    </staff>\n" +
            "    <staff id=\"1002\">\n" +
            "        <name>yflow</name>\n" +
            "        <role>admin</role>\n" +
            "        <salary currency=\"EUR\">8000</salary>\n" +
            "        <bio><![CDATA[a & b]]></bio>\n" +
            "    </staff>\n" +
            "</company>";

    public static void main(String[] args) {

        // String to XML Document
        Document document = convertStringToXml(str);

        // XML Document to String
        String xml = convertXmlDocumentToString(document);

        System.out.println(xml);

    }

    private static String convertXmlDocumentToString(Document doc) {
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat());

        StringWriter result = new StringWriter();
        try {
            xmlOutput.output(doc, result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result.toString();
    }

    private static Document convertStringToXml(String xmlString) {

        SAXBuilder sax = new SAXBuilder();

        // https://rules.sonarsource.com/java/RSPEC-2755
        // prevent xxe
        sax.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        sax.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

        try {

            Document doc = sax.build(new StringReader(xmlString));
            return doc;

        } catch (JDOMException | IOException e) {
            throw new RuntimeException(e);
        }

    }

}
<?xml version="1.0" encoding="UTF-8"?>
  <company>
    <staff id="1001">
      <name>sharecs</name>
      <role>support</role>
      <salary currency="USD">5000</salary>
      <!-- for special characters like < &, need CDATA -->
      <bio><![CDATA[HTML tag <code>testing</code>]]></bio>
    </staff>
    <staff id="1002">
      <name>yflow</name>
      <role>admin</role>
      <salary currency="EUR">8000</salary>
      <bio><![CDATA[a & b]]></bio>
    </staff>
  </company>

Cảm ơn các bạn đã ghé thăm. Chúc các bạn thành công!

0 lượt xem | 0 bình luận