2020년 4월 14일 화요일

java로 xml 생성

모듈화 하고자 한번 만들어 보았음

@RequestMapping(value = "/xmlWrite", method = RequestMethod.POST)
public String xmlWrite (HttpServletRequest request) throws ParserConfigurationException, SAXException, IOException {
LinkedHashMap <String, String> map = new LinkedHashMap <String,String>();

map.put("systemId", "XXXXXXXX");
map.put("pmsUserId", "PV2Bu2A0");
map.put("pmsPassword", "g?Z+yy5U5!LR");
map.put("pmsPassword2", "g?Z+yy5U5!LRPPPPP");
map.put("commonRequest", "null");

map.put("systemCode", "1");
map.put("outputId", "D8098420100120000001");
map.put("outputTarget", "null");

map.put("systemTest", "999");
map.put("outputIdTest", "TEADF34");
map.put("outputTargetTest", "null");

String sTemp = StringUtil.xmlWrite(map);
System.out.println(sTemp);

return sTemp;

}


public static String xmlWrite (LinkedHashMap<String, String> map  ) throws ParserConfigurationException {

Document doc = null;
DocumentBuilderFactory factory = null;
factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();

Element prj_list = doc.createElement("arg0");
doc.appendChild(prj_list);
 
ArrayList<String> arrList = new ArrayList<>();
for(String key: map.keySet()){
String sValue  = "";
sValue = map.get(key);
if(sValue.equals("null")){
arrList.add(key);
}
}
int iTest =1;
int iii = 0;
int iAdd =0;
int iOverlap=0;
if(arrList.size() > 0){
for(int i=0; i<arrList.size(); i++){
if(map.size() > 0){
for(String key: map.keySet()){
String sValue  = "";
sValue = map.get(key);

if(key.equals(arrList.get(i))){
Element code = null;
if(sValue.equals("null")){//3개면 3번
code = doc.createElement(key);
prj_list.appendChild(code);
iAdd++;
for(String key2: map.keySet()){//전체 횟수 만큼 반복
String sValue2  = "";
sValue2 = map.get(key2);
if(sValue2.equals("null")){//해쉬맵에 값 null 만나면

}else{
if(iAdd==iTest){
if(iOverlap == iii){
Element name = doc.createElement(key2);
name.appendChild(doc.createTextNode(sValue2));
code.appendChild(name);

prj_list.appendChild(code);
iOverlap++;

}else{
if(iii-iOverlap == 1){
System.out.println(iii-iOverlap);
iOverlap++;
break;
}
}
}
}
iii++;
}
iTest++;
iii=0;
}
}
}
}
}
}


TransformerFactory tr_factory = TransformerFactory.newInstance();
String xmlStr = "";    
try {
    StringWriter sw = new StringWriter();
    Properties output = new Properties();
    output.setProperty(OutputKeys.INDENT, "yes");
    output.setProperty(OutputKeys.ENCODING, "EUC-KR");
    Transformer transformer = tr_factory.newTransformer();
    transformer.setOutputProperties(output);
    transformer.transform(new DOMSource(doc), new StreamResult(sw));
    xmlStr = sw.getBuffer ().toString ();
//     System.out.println("::::::::::::::"+xmlStr);
}
catch (Exception e)
{
    e.getMessage();
}

return xmlStr;
}

댓글 없음:

댓글 쓰기