'Insert nested XLM nodes if node doesn't exist using Groovy/JavaScript
Below is the XML I am working with
<Root>
<Employee>
<EmployeeNumber>10105950</EmployeeNumber>
<LastName>Myers Jr</LastName>
<FirstName>Ezell</FirstName>
<MiddleName/>
<JobTitle>Tech Shield Strapper</JobTitle>
<Manager>N</Manager>
<ManagerID>50501273</ManagerID>
<BusinessEmail>[email protected]</BusinessEmail>
<Location>TX06</Location>
<CostCenter>10200011</CostCenter>
<HomeLocationCode>TX06 10200011</HomeLocationCode>
<cust_HomeLocationCode>
<cust_LocationCode>30</cust_LocationCode>
</cust_HomeLocationCode>
<Username>myers10105950</Username>
<CostCenterName>JASPER OSB Finishing Techshield</CostCenterName>
<WorkContract>A2</WorkContract>
<HireDate>11/14/2002</HireDate>
<PreferredLanguage>1706</PreferredLanguage>
<PreferredName>Ezell</PreferredName>
</Employee>
<Employee>
<EmployeeNumber>10105951</EmployeeNumber>
<LastName>Bean</LastName>
<FirstName>David</FirstName>
<MiddleName>A</MiddleName>
<JobTitle>Sr. FP&A Analyst</JobTitle>
<Manager>N</Manager>
<ManagerID>10129003</ManagerID>
<BusinessEmail>[email protected]</BusinessEmail>
<Location>TX06</Location>
<CostCenter>11000152</CostCenter>
<HomeLocationCode>TX06 11000152</HomeLocationCode>
<Username>beanda</Username>
<CostCenterName>OSB Finance</CostCenterName>
<WorkContract>A2</WorkContract>
<HireDate>07/05/1994</HireDate>
<PreferredLanguage>1706</PreferredLanguage>
<PreferredName>David</PreferredName>
</Employee>
</Root>
I need help writing a groovy script or javascript to evaluate the XML. If <cust_HomeLocationCode> and its contents exist, then skip, else insert the node with <cust_LocationCode> value equaling '1'.
So far I have been able to add just the <cust_HomeLocationCode> node using below code
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.xml.XmlUtil;
import groovy.util.*;
def Message processData(Message message) {
def body = message.getBody(java.lang.String);
def root = new XmlParser().parseText(body)
root.each { Employee ->
Employee.appendNode("cust_HomeLocationCode", "newfield")
}
message.setBody(XmlUtil.serialize(root));
return message;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
