728x90
반응형
XML 데이터를 String으로 변환하는 방법이 잘 정리 되있길래 정리해본다.
샘플코드
package app.model.com;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XMLtoString {
public static void main(String[] args) throws IOException {
/**
* 샘플용 XML문자열
*/
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
/**
* xmlStr을 Document으로 변환하는 convertStringToDocument 함수 호출
*/
Document doc = convertStringToDocument(xmlStr);
/**
* document를 String으로 변환하는 convertDocumentToString 함수 호출
*/
String str = convertDocumentToString(doc);
System.out.println(str.getClass().getName());
System.out.println(str);
}
private static String convertDocumentToString(Document doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) );
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
결과화면
어려운 거 없고, 그냥 위의 함수를 조금 활용해서 잘 쓰면 될 거 같다. 너무 정리가 잘되어 있어서 그냥 가져옴..
참조 : Java Convert String to XML Document and XML Document to String
728x90
반응형