Android xml get node value null - java

i have a xml
<DatosClientes>
<User>Prueba</User>
<intUserNumber>1487</intUserNumber>
<IdUser>1328</IdUser>
</DatosClientes>
How to read data in android ? when run all time return null in node value
public static void Parse(String response){
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(response));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList datos = doc.getElementsByTagName("DatosClientes");
XmlParse parser = new XmlParse();
for (int i = 0; i < datos.getLength(); i++) {
Node node = datos.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("User");
Log.e("log",String.valueOf(nameList.item(0).getNodeValue()));
}
}catch (Exception e){
e.printStackTrace();
}
}
my objetive is finally read value and convert into ArrayList

It sounds like you are trying to get a list of the values in the XML? That is, you want:
{ "Prueba", "1487", "1328" }
For that, you can do something like:
public static final String XML_CONTENT =
"<DatosClientes>"
+ "<User>Prueba</User>"
+ "<intUserNumber>1487</intUserNumber>"
+ "<IdUser>1328</IdUser>"
+ "</DatosClientes>";
public static final Element getRootNode(final String xml) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
return document.getDocumentElement();
} catch (ParserConfigurationException | SAXException | IOException exception) {
System.err.println(exception.getMessage());
return null;
}
}
public static final List<String> getValuesFromXml(final String xmlContent) {
Element root = getRootNode(xmlContent);
NodeList nodes = root.getElementsByTagName("*");
List<String> values = new ArrayList<>();
for (int index = 0; index < nodes.getLength(); index++) {
final String nodeValue = nodes.item(index).getTextContent();
values.add(nodeValue);
System.out.println(nodeValue);
}
return values;
}
public static void main (String[] args) {
final List<String> nodeValues = getValuesFromXml(XML_CONTENT);
}

Related

i am getting null data when i get the data from xml nodes

I'm receiving 'null' values when I try to read values from XML nodes.
Structure example:
<document>
<user>ss</user>
<password >ssss</password >
</document>
Result: o/p [user: null] [password: null]
This is my code:
public class stres() {
public static void main(String[] args) throws SQLException, ParserConfigurationException, SAXException, IOException {
try {
String resulturl ="my url";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(resulturl);
NodeList documentt = doc.getElementsByTagName("document");
for (int i = 0; i < documentt.getLength(); i++) {
Element data = (Element) documentt.item(0);
Node user = data.getElementsByTagName("user").item(0);
Node password = data.getElementsByTagName("password").item(0);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Error in reading XML in Java

I need to read a XML file and when I run the folllowing error message apears:
Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to org.w3c.dom.Element
at leituraxml.LeituraXML.main(LeituraXML.java:40)
The Code:
public class LeituraXML {
public static void main(String[] args) throws SAXException, IOException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("C:\\catalogo.xml");
NodeList catalogo = doc.getElementsByTagName("rec");
int tamanhoDoCatalogo = catalogo.getLength();
for (int i = 0; i < tamanhoDoCatalogo; i++){
Node noExemplar = catalogo.item(i);
if (noExemplar.getNodeType()==Node.ELEMENT_NODE){
Element elementoExemplar = (Element)noExemplar;
NodeList listaDeExemplares = elementoExemplar.getChildNodes();
for (int j = 0; j<listaDeExemplares.getLength(); i++){
Node noFilho = listaDeExemplares.item(j);
if(noFilho.getNodeType()==Node.ELEMENT_NODE);
Element elementoFilho = (Element) noFilho;
switch(elementoFilho.getTagName()){
case "v018":
System.out.println(elementoFilho.getTextContent());
}
}
}
}
} catch (ParserConfigurationException ex) {
Logger.getLogger(LeituraXML.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
XML file snippet:
<rec>
<v001>001</v001>
<v002>201260927231</v002>
<v003>616.890231</v003>
<v005>7</v005>
<v006>m</v006>
<v007>^a115001^b1^c1^d20100000^e2^fOvernight^m1</v007>
<v007>^a115002^b2^c1^d20100000^e1^m2</v007>
<v007>^a115003^b3^c1^d20100000^e1^m3</v007>
<v007>^a115004^b4^c1^d20100000^e1^m4</v007>
<v007>^a115005^b5^c1^d20100000^e1^m5</v007>
<v007>^a115006^b6^c1^d20100000^e1^m6</v007>
<v008>http://www.conselho.saude.gov.br/14cns/docs/constituicaofederal.pdf</v008>
<v016>ROCHA, Ruth Mylius</v016>
<v018>Enfermagem em Saúde Mental</v018>
<v020>187</v020>
<v022>9</v022>
<v040>1</v040>
<v061>-187iografia: p. 182-187</v061>
<v062>Ed. SENAC Nacional</v062>
<v063>2. ed. atual. e ampl</v063>
<v064>2005</v064>
<v065>20050000</v065>
<v066>Rio de Janeiro</v066>
<v069>8574581658</v069>
<v070>http://phl.sjdr.ifsudestemg.edu.br:8080/imagens/Enfermagem em saúde mental.jpg</v070>
<v085>4</v085>
<v087>Enfermagem psiquiátrica</v087>
<v087>Saúde mental</v087>
<v087>Substâncias psicoativas</v087>
<v087>Psiquiatria</v087>
<v090>b</v090>
<v096>http://www.conselho.saude.gov.br/14cns/docs/constituicaofederal.pdf</v096>
<v103>R672e</v103>
<v998>1</v998>
<v999>uper^bsuper^bsuper^bsuper</v999>
<v999>^d20180412^h103632^bthais</v999>
</rec>

XPath witn namespace - query gives not results

Without using a namespace the XPath example worked fine. A list is printed. With the namespace added, no result is returned.
How can I use namespaces and XPath properly?
My sample (minimalized) xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<nodespace:Employees xmlns:nodespace="my_unique_namespace_name">
<nodespace:Employee id="1">
<nodespace:age>29</nodespace:age>
<nodespace:name>Pankaj</nodespace:name>
<nodespace:gender>Male</nodespace:gender>
<nodespace:role>Java Developer</nodespace:role>
</nodespace:Employee>
<nodespace:Employee id="2">
<nodespace:age>35</nodespace:age>
<nodespace:name>Lisa</nodespace:name>
<nodespace:gender>Female</nodespace:gender>
<nodespace:role>CEO</nodespace:role>
</nodespace:Employee>
</nodespace:Employees>
The XPath Java source code is:
public class XpathNamespaceTest {
public static final String PREFIX_NAME = "bdn";
public static final String NODESPACE_UNIQUE_NAME = "nodespace";
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
try {
ClassLoader classLoader = new XpathNamespaceTest().getClass().getClassLoader();
URL resource = classLoader.getResource("employees_namespace.xml");
File file = new File( resource.getFile());
builder = factory.newDocumentBuilder();
doc = builder.parse(file);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
#Override
public Iterator getPrefixes(String arg0) { return null; }
#Override
public String getPrefix(String ns) {
if(ns.equals(NODESPACE_UNIQUE_NAME)) {
return PREFIX_NAME;
}
return null;
}
#Override
public String getNamespaceURI(String arg0) {
if (PREFIX_NAME.equals(arg0)) {
return NODESPACE_UNIQUE_NAME;
}
return null;
}
});
List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath, int age) {
List<String> list = new ArrayList<>();
try {
XPathExpression expr = xpath.compile("/bdn:Employees/bdn:Employee[bdn:age>" + age + "]/bdn:name/text()");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) list.add(nodes.item(i).getNodeValue());
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
}
}
The namespace URI is my_unique_namespace_name so you need
public static final String NODESPACE_UNIQUE_NAME = "my_unique_namespace_name";

Junit4 test implementation with parameters passed from XML, (attribute value + nodevalue)?

I know I can hardcode it (parse xml, extract), but is there a way to feed (attribute value + nodevalue) like it is done with Feed4TestNG (it currently support only csv, and excel files)?
I am new to Java, and any expert insight would be helpful. Thanks!
The body of a #Parameters is not limited to data only, you are able to use any java code you like in this method, including throwing exceptions:
#Parameters
public static Collection<Object[]> data() throws IOException {
List<Object[]> data = new ArrayList<>();
// replace getClass() with <nameofclass>.class
try(InputStream in = this.getClass().getResourceAsStream()) {
//parse body here
data.add(new Object[]{attribute, value});
}
return data;
}
Depending on what XML framework you use, you need to parse your XML nodes, and put it in the list, that you are going to return.
So this is what I end up doing here:
Please submit your correction if you think I can improve my code.
.
#RunWith(Parameterized.class)
public class DataDrivenTests {
private String c;
private String b;
private static Collection<Object[]> a;
#Parameters
public static Collection<Object[]> xmlData() throws IOException{
File file = new File("xmlfile.xml");
InputStream xml1 = new FileInputStream(file);
return new xmlData(xml1).getData();
}
public DataDrivenTests(String c, String b) {
super();
this.c = c;
this.b = b;
}
#Test
public void shouldCalculateATimesB() {
boolean assertion = false;
if(c.equals(Parser.parse("Parse this string to Attribute and Value"))){
assertion = true;
}
assertTrue(assertion);
}
}
xmlData.java
public class xmlData{
private transient Collection<Object[]> data = null;
public xmlData(final InputStream xml)throws IOException{
this.data = loadFromXml(xml);
}
public Collection<Object[]> getData(){
return data;
}
private Collection<Object[]> loadFromXml(final InputStream xml)
throws IOException {
List <Object[]> ism_code_map = new ArrayList<Object[]>();
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile("//e");
NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
for (int i =0; i< nodes.getLength(); i++){
Node nNode = nodes.item(i);
//System.out.println("\nCurrent Element:" + nNode.getTextContent());
if (nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
if(eElement.getAttribute("attrname") != null && !eElement.getAttribute("attrname").isEmpty()){
code_map.add(new Object[]{"attrname",eElement.getAttribute("attrname")});
}
}catch(ParserConfigurationException e){
e.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(XPathExpressionException e){
e.printStackTrace();
}
catch(NullPointerException e){
e.printStackTrace();
}
return code_map;
}
}

XPath with namespace in Java

I would like to get all the content in between the tags but I do not know how to do this because of the urn: namespace.
<urn:ResponseStatus version="1.0" xmlns:urn="urn:camera-org">
<urn:requestURL>/CAMERA/Streaming/status</urn:requestURL>
<urn:statusCode>4</urn:statusCode>
<urn:statusString>Invalid Operation</urn:statusString>
<urn:id>0</urn:id>
</urn:ResponseStatus>
Any ideas?
Short answer: use XPath local-name(). Like this: xPathFactory.newXPath().compile("//*[local-name()='requestURL']/text()"); will return /CAMERA/Streaming/status
Or you can implement a NamespaceContext that maps namespaces names and URIs and set it on the XPath object before querying.
Take a look at this blog article, Update: the article is down, you can see it on webarchive
Solution 1 sample:
XPath xpath = XPathFactory.newInstance().newXPath();
String responseStatus = xpath.evaluate("//*[local-name()='ResponseStatus']/text()", document);
System.out.println("-> " + responseStatus);
Solution 2 sample:
// load the Document
Document document = ...;
NamespaceContext ctx = new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return prefix.equals("urn") ? "urn:camera-org" : null;
}
public Iterator getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
};
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(ctx);
String responseStatus = xpath.evaluate("//urn:ResponseStatus/text()", document);
System.out.println("-> " + responseStatus);
Edit
This is a complete example, it correctly retrieve the element:
String xml = "<urn:ResponseStatus version=\"1.0\" xmlns:urn=\"urn:camera-org\">\r\n" + //
"\r\n" + //
"<urn:requestURL>/CAMERA/Streaming/status</urn:requestURL>\r\n" + //
"<urn:statusCode>4</urn:statusCode>\r\n" + //
"<urn:statusString>Invalid Operation</urn:statusString>\r\n" + //
"<urn:id>0</urn:id>\r\n" + //
"\r\n" + //
"</urn:ResponseStatus>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return prefix.equals("urn") ? "urn:camera-org" : null;
}
public Iterator<?> getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
});
XPathExpression expr = xpath.compile("//urn:ResponseStatus");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
Node currentItem = nodes.item(i);
System.out.println("found node -> " + currentItem.getLocalName() + " (namespace: " + currentItem.getNamespaceURI() + ")");
}
XML xpath with Namespace
Simple XML
String namespaceXML = "<?xml version='1.0' ?><information><person id='1'><name>Deep</name><age>34</age><gender>Male</gender></person> <person id='2'><name>Kumar</name><age>24</age><gender>Male</gender></person> <person id='3'><name>Deepali</name><age>19</age><gender>Female</gender></person><!-- more persons... --></information>";
String jsonString = "{}";
String expression = "//information";
Name space XML
String namespaceXML = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><m:NumberToDollarsResponse xmlns:m=\"http://www.dataaccess.com/webservicesserver/\"><m:NumberToDollarsResult>nine hundred and ninety nine dollars</m:NumberToDollarsResult></m:NumberToDollarsResponse></soap:Body></soap:Envelope>";
String jsonString = "{'soap':'http://schemas.xmlsoap.org/soap/envelope/', 'm':'http://www.dataaccess.com/webservicesserver/'}";
String expression = "//m:NumberToDollarsResponse/m:NumberToDollarsResult/text()";
Supply namespace xml file as a string, to asscerionXpath(namespaceXML, jsonString, expression) method and get result in the form of text/node.
text() : nine hundred and ninety nine dollars
node :
<m:NumberToDollarsResult xmlns:m="http://www.dataaccess.com/webservicesserver/">
nine hundred and ninety nine dollars
</m:NumberToDollarsResult>
public static String asscerionXpath(String namespaceXML, String jsonString, String expression){
if(namespaceXML.indexOf("><") > -1) namespaceXML = namespaceXML.replace("><", ">\r\n<");
if(jsonString.indexOf("'") > -1) jsonString = jsonString.replace("'", "\"");
System.out.println("namespaceXML : \n"+namespaceXML);
System.out.println("nsmespaces : \n"+jsonString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document source = builder.parse( string2Source(namespaceXML) );
XPath xpath = XPathFactory.newInstance().newXPath();
addNameSpaces(jsonString, xpath);
// An XPath expression is not thread-safe. Make sure it is accessible by only one Thread.
XPathExpression expr = xpath.compile(expression);
// The NodeList interface provides the abstraction of an ordered collection of nodes,
NodeList nodes = (org.w3c.dom.NodeList) expr.evaluate(source, XPathConstants.NODESET);;
Node tree_base = nodes.item(0);
return document2String(tree_base);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
System.out.println("If the expression cannot be evaluated.");
}
return "";
}
static InputSource string2Source( String str ) {
InputSource inputSource = new InputSource( new StringReader( str ) );
return inputSource;
}
static void addNameSpaces(String jsonString, XPath xpath) {
JSONParser parser = new JSONParser();
try {
JSONObject namespaces = (JSONObject) parser.parse(jsonString);
if (namespaces.size() > 0) {
final JSONObject declaredPrefix = namespaces; // To access in Inner-class.
NamespaceContext nameSpace = new NamespaceContext() {
// To get all prefixes bound to a Namespace URI in the current scope, XPath 1.0 specification
// --> "no prefix means no namespace"
public String getNamespaceURI(String prefix) {
Iterator<?> key = declaredPrefix.keySet().iterator();
System.out.println("Keys : "+key.toString());
while (key.hasNext()) {
String name = key.next().toString();
if (prefix.equals(name)) {
System.out.println(declaredPrefix.get(name));
return declaredPrefix.get(name).toString();
}
}
return "";
}
public Iterator<?> getPrefixes(String val) {
return null;
}
public String getPrefix(String uri) {
return null;
}
};// Inner class.
xpath.setNamespaceContext( nameSpace );
}
} catch ( org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}

Categories