I have a group of working code to construct an XML Request in certain specific format as per below. But the logic was just hardcoded example emaillist.appendChild
document.createElement
and so on. Is there any better way of achieving the same result? Maybe using some Stub or Custom XML type Java Entity?
public void setXML() throws JAXBException, ParserConfigurationException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element emaillist = document.createElement("EMAILLIST");
Element templateID = document.createElement("TemplateID");
templateID.setTextContent("1");
Element campaignID = document.createElement("CampaignID");
campaignID.setTextContent("100");
Element campaignName = document.createElement("CampaignName");
campaignName.setTextContent("Test Campaign Using XML DS");
Element category = document.createElement("Category");
category.setTextContent("Trigger");
Element email = document.createElement("Email");
email.setTextContent("test@test.com");
Element subject = document.createElement("Subject");
subject.setTextContent("Transactional Submissions");
Element senderEmail = document.createElement("SenderEmail");
senderEmail.setTextContent("support@test");
Element emailBody = document.createElement("EmailBody");
Element html = document.createElement("html");
Element head = document.createElement("head");
Element title = document.createElement("title");
title.setTextContent("This is test Title : " + ZonedDateTime.now());
head.appendChild(title);
Element body = document.createElement("body");
html.appendChild(head);
html.appendChild(body);
emailBody.appendChild(html);
emaillist.appendChild(templateID);
emaillist.appendChild(campaignID);
emaillist.appendChild(campaignName);
emaillist.appendChild(category);
emaillist.appendChild(email);
emaillist.appendChild(subject);
emaillist.appendChild(senderEmail);
emaillist.appendChild(emailBody);
System.out.println(emaillist);
}
Sample Required Output
<EMAILLIST
xmlns:ns2="TransactionalSubmissionsSvcs"
xmlns="">
<TemplateID>1</TemplateID>
<CampaignID>100</CampaignID>
<CampaignName>Test Campaign Using XML DS</CampaignName>
<Category>Trigger</Category>
<Email>test@test.com.my</Email>
<Subject>Transactional Submissions</Subject>
<SenderEmail>test@test.com.my</SenderEmail>
<EmailBody>
<html>
<head>
<title>This is test Title : 2019-03-17T20:32:43.649+08:00</title>
</head>
<body/>
</html>
</EmailBody>
</EMAILLIST>