Expand my Community achievements bar.

SOLVED

last name value is not coming from xml File

Avatar

Level 2

Hi All,

 

I have written the below JAVA file for reading my XML file and provide me the all LastName Value.

 

But if I am doing this like using below , then I am getting error.

//logger.info("LASTNAME VALUE from ==== " + element.getElementsByTagName("LastName").item(i).getTextContent());

 

********************* MY XML FILE ****************************

<?xml version="1.0" encoding="utf-8"?>
<Loans>
<UniqueEntry>
<LastName>test1</LastName><PreferredName>sonu</PreferredName><UniqueNumber>1</UniqueNumber>
</UniqueEntry>
 
<UniqueEntry>
<LastName>test2</LastName><PreferredName>monu</PreferredName><UniqueNumber>2</UniqueNumber>
</UniqueEntry>
 
<UniqueEntry>
<LastName>test3</LastName><PreferredName>dinu</PreferredName><UniqueNumber>3</UniqueNumber>
</UniqueEntry>
</Loans>
 
********************************* MY JAVA FILE *******************************
 
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
 
import javax.jcr.Node;
import javax.jcr.Session;
import javax.servlet.Servlet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
 
import org.apache.http.HttpStatus;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
@component(service = Servlet.class)
@SlingServletResourceTypes(resourceTypes = { "wknd/components/form/search-unique" }, methods = {
HttpConstants.METHOD_POST }, extensions = "json")
public class SearchUniqueNumberServlet extends SlingAllMethodsServlet {
 
private static final long serialVersionUID = -8864935516234206658L;
 
private final Logger logger = LoggerFactory.getLogger(getClass());
 
ResourceResolverFactory resourceResolverFactory;
ResourceResolver resourceResolver;
Session session;
 
/**
* @throws IOException
*/
public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
logger.info("INSIDE DO POST");
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> responseData = new HashMap<>();
try {
 
String propertyLastNameValue = request.getParameter("lastName");
logger.info("LastName INSIDE SEARCH  ====== " + propertyLastNameValue);
resourceResolver = request.getResourceResolver();
Resource resource = resourceResolver.getResource("/content/dam/wknd/en/site/testfile.xml");
Node fileNode = resource.adaptTo(Node.class);
 
InputStream xmlContent = JcrUtils.readFile(fileNode);
 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 
DocumentBuilder builder = factory.newDocumentBuilder();
 
Document doc = builder.parse(xmlContent);
 
Element element = doc.getDocumentElement();
 
logger.info("Root element UniqueEntry : " + element.getElementsByTagName("UniqueEntry"));
 
// get all child nodes
NodeList nodes = element.getChildNodes();
 
for (int i = 0; i < nodes.getLength(); i++) {
logger.info("nodes ==== " + nodes.item(i).getTextContent()); //OUTPUT IS test1sonu1 , test2monu2 and test3dinu3
//logger.info("LASTNAME VALUE from ==== " + element.getElementsByTagName("LastName").item(i).getTextContent());
//responseData.put("LASTNAME :: ", element.getElementsByTagName("LastName").item(i).getTextContent());
}
catch (Exception exception) {
response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, exception.getMessage());
}
finally {
response.setContentType("application/json");
response.setHeader("Cache-Control", "nocache");
response.setCharacterEncoding("utf-8");
response.getWriter().println(objectMapper.writeValueAsString(responseData));
}
}
}

 

Can anyone please help me how can I do this ?

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@SunitaCh 

Can you add the specific error that you are getting during accessing the element .

Also can you update the reading part with the below lines and see if that works

 

 // first line optional
 // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
 doc.getDocumentElement().normalize();
 NodeList list = doc.getElementsByTagName("UniqueEntry");
 for (int temp = 0; temp < list.getLength(); temp++) {
 Node node = list.item(temp);
 if (node.getNodeType() == Node.ELEMENT_NODE) {
 Element element = (Element) node;
 String lastname=element.getElementsByTagName("LastName").item(0).getTextContent();
 }
}

View solution in original post

2 Replies

Avatar

Correct answer by
Community Advisor

@SunitaCh 

Can you add the specific error that you are getting during accessing the element .

Also can you update the reading part with the below lines and see if that works

 

 // first line optional
 // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
 doc.getDocumentElement().normalize();
 NodeList list = doc.getElementsByTagName("UniqueEntry");
 for (int temp = 0; temp < list.getLength(); temp++) {
 Node node = list.item(temp);
 if (node.getNodeType() == Node.ELEMENT_NODE) {
 Element element = (Element) node;
 String lastname=element.getElementsByTagName("LastName").item(0).getTextContent();
 }
}

Avatar

Administrator

@SunitaCh Did you find the suggestion from @sherinregi helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni