What's wrong in this code? It gives me null everytime. I have no idea how to repair it, because in ordinary Java Application it works.
#WebMethod(operationName = "getColor")
public String getColor(#WebParam(name = "regNr") String regNr) {
String kolor=null;
try {
File fXmlFile = new File("/base.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("person");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nNode;
String id = ""+ getValue("id",element);
if (regNr.equals(id)) {
color = element.getElementsByTagName("color").item(0).getTextContent();
return color;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return color;
}
I think (not sure because I don't know at which point it gives you null) you have to remove the / form the file name to become only base.xml
Related
I want to iterate through XML file using JDOM and I get a NullPointerException in line 67 on my code, I try to store the XML date into a List:
public class ProduitImportXml {
public static List<Produit> getProduits() {
List<Produit> produitsList = new ArrayList<Produit>();
try {
File fXmlFile = new File("ProduitData.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize(); // optional --------
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("produits");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nNode;
int len = nNode.getChildNodes().getLength();
for (int i = 0; i<len; i++)
{
Produit p=new Produit(
el.getElementsByTagName("idProduit").item(0).getTextContent(),//return NullPointerException
el.getElementsByTagName("type").item(0).getTextContent(),
el.getElementsByTagName("marque").item(0).getTextContent(),
el.getElementsByTagName("modele").item(0).getTextContent(),
el.getElementsByTagName("libelle").item(0).getTextContent(),
el.getElementsByTagName("codeTac").item(0).getTextContent(),
el.getElementsByTagName("genCode").item(0).getTextContent());
produitsList.add(p);
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return produitsList;
}
}
Any idea about how to solve this problem, this is the console message that I catch:
MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList
class HtmlTagmodifier {
public String htmlFileWriter(String cfile, String Listname, String Nodename, String nodevalue) {
try {
File fhtmlFile = new File(cfile);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fhtmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(Listname);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
eElement.getElementsByTagName(Nodename).item(0).setTextContent(nodevalue);
}
}
Source source = new DOMSource(doc);
Result htmlresult = new StreamResult(fhtmlFile);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, htmlresult);
result2 = "Success";
} catch (Exception e) {
e.printStackTrace();
log.error("Error in html file writing " + e.toString());
JOptionPane.showMessageDialog(null, "Error in html file writing " + e.toString());
result2 = "Failed";
}
return result2;
}
public static void main(String[] args) {
HtmlTagmodifier.htmlfilewriter("test.html", "details", "customername", "customernamexxxxxx");
}
}
Output:
when i use this method to modify the tag values of html,tag name is changed successfully but meta data tag is added again in the html
please give me suggestion.
I've been trying to make this work for longer than I'd like to say now and just can't figure out why it won't recognize the password,I get a null pointer exception on this line if (userPassword.getTextContent().equals(password)
Here is the method
public class XML {
public static boolean login(String email, String password) {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("data.xml");
Element root = document.getDocumentElement();
NodeList nList = root.getChildNodes();
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element users = (Element) nNode;
if (users.getNodeName().compareTo("users") == 0) {
NodeList userList = users.getChildNodes();
for (int j = 0; j < userList.getLength(); j++) {
Node userNode = userList.item(j);
NodeList AttributeList = userNode.getChildNodes();
Node userPassword = AttributeList.item(1);
Node userEmail = AttributeList.item(0);
if (userPassword.getTextContent().equals(password)
&& userEmail.getTextContent().equals(email)) {
return true;
}
}
}
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
}
return false;
}
Attribute nodes don't have text content but a value. You should use the following construct to retrieve it :
Node userNode = userList.item(j);
String attributeValue = userNode.getAttribute("attributeName")
Alternatively since you already have the attributes Nodes, you could cast them to org.w3c.dom.Attr and use their .getValue() method.
The XML file contains Employee (with empID, empName, empCode). In some situation empCode is missing.
<Employee><Detail><empID>1</empID><empName>Abhi</empName><empCode>One</empCode>
</Detail>
<Detail><empID>2</empID><empName>Amit</empName>
</Detail>
</Employee>
I am getting the Null pointer Exception while calling the getTagValue() method for "empCode" as there is no tag available with the name in XML.
Java Code :
try
{
File xmlFile = new File("New.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Detail");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
EmpDetail empInfo = new EmpDetail();
empInfo.SetEmpID(getTagValue("empID", eElement));
empInfo.SetEmpName(getTagValue("empName",eElement));
empInfo.SetEmpCode(getTagValue("empCode",eElement));
DBConnector.SaveinDB(empInfo);
}
}
}
catch (Exception e)
{
System.out.println("Error: ");
e.printStackTrace();
}
}
private static String getTagValue(String sTag, Element eElement)
{
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
if(nValue == null)
return null;
return insertEscapeSequance(nValue.getNodeValue());
}
private static String insertEscapeSequance(String str)
{
String returnstr = "";
String[] strarr = str.split("'");
returnstr = strarr[0];
for(int i=1;i<strarr.length;i++)
{
returnstr = returnstr + "\\'" + strarr[i];
}
return returnstr;
}
Now I want to save the XML data into sql like this :
1 Abhi One
2 Amit null
I tried so many links but not success. Can someone please help me
If this is possible that there is no such value, then simply handle it like that:
if(getTagValue("empCode",eElement) != null){
empInfo.SetEmpCode(getTagValue("empCode",eElement));
}
Regarding to adding them into SQL, do the same check while creating your statement. As SQL NULL type exists
The problem is caused by eElement.getElementsByTagName(sTag).item(0). The statement returns the first node specified by sTag. In the case of empCode, null is returned, and calling getChildNodes() will raise a null pointer exception.
Try:
Node node = eElement.getElementsByTagName(sTag).item(0);
if (node != null) {
Node nValue = node.getChildNodes().item(0);
if (nValue != null) {
return insertEscapeSequance(nValue.getNodeValue());
}
}
return null;
I need to receive all the text alone from an xml file for receiving the specific tag i use this code. But i am not sure how to parse all the text from the XML i the XML files are different i don't know their root node and child nodes but i need the text alone from the xml.
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(streamLimiter.getFile());
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("employee");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList nlList = eElement.getElementsByTagName("firstname")
.item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
System.out.println("First Name : "
+ nValue.getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
Quoting jsight's reply in this post: Getting XML Node text value with Java DOM
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
String xml = "<add job=\"351\">\n"
+ " <tag>foobar</tag>\n"
+ " <tag>foobar2</tag>\n"
+ "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
org.w3c.dom.Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an, an2;
for (int i = 0; i < nl.getLength(); i++) {
an = nl.item(i);
if (an.getNodeType() == Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for (int i2 = 0; i2 < nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if (an2.hasChildNodes()) {
System.out.println(an2.getFirstChild().getTextContent());
}
if (an2.hasChildNodes()) {
System.out.println(an2.getFirstChild().getNodeValue());
}
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
}
}
Output:
#text: type (3):
foobar
foobar
#text: type (3):
foobar2
Adapt this code to your problem and it should work.