Passing integer as string in java - java

I am parsing an xml file which has one table as below:
<table name="categoryAttributeTable">
<row>
<field name="CID">201</field>
<field name="name">page_title</field>
<field name="value">Spotlight</field>
</row>
<row>
<field name="CID">301</field>
<field name="name">page_title</field>
<field name="value">Oryx highlights</field>
</row>
<row>
<field name="CID">501</field>
<field name="name">page_title</field>
<field name="value">Little Taster</field>
</row>
</table>
I want to search value of CID 301 for which the ans should be Oryx highlights but i am getting Spotlight as ans which is the value of CID 201. Why this might be happening???
My java code is :
public static void main(String argv[]) {
try {
File fXmlFile = new File("/home/media.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("table");
System.out.println("----------------------------");
String titlevalue=null;
String cidvalue=null;
String lidvalue=null;
List a = new ArrayList();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if(eElement.getAttribute("name").equalsIgnoreCase("categoryAttributeTable"))
{
NodeList nList1 = eElement.getElementsByTagName("row");
for (int temp1 = 0; temp1 < nList1.getLength(); temp1++) {
Node nNode1 = nList1.item(temp1);
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) nNode1;
NodeList nList2 = eElement1.getElementsByTagName("field");
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Node nNode2 = nList2.item(temp2);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
if(eElement2.getAttribute("name").equalsIgnoreCase("value"))
{
titlevalue=eElement2.getTextContent();
// System.out.println(" Title value :: "+titlevalue);
}
if(eElement2.getAttribute("name").equalsIgnoreCase("CID") && (eElement2.getTextContent().equals(String.valueOf(301))))
{
System.out.println(" Title value :: "+titlevalue);
}
}
}
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
In eElement2.getAttribute("name").equalsIgnoreCase() if i pass string then the output is coming as expected but if i pass integer as string then it is showing previous level's ans.
Please help me...

See this...
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXMLFile {public static void main(String argv[]) {
try {
File fXmlFile = new File("src/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("table");
System.out.println("----------------------------");
String titlevalue=null;
String cidvalue=null;
String lidvalue=null;
List<String> valueList=new ArrayList<String>();
List<String> cidList=new ArrayList<String>();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if(eElement.getAttribute("name").equalsIgnoreCase("categoryAttributeTable"))
{
NodeList nList1 = eElement.getElementsByTagName("row");
for (int temp1 = 0; temp1 < nList1.getLength(); temp1++) {
Node nNode1 = nList1.item(temp1);
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) nNode1;
NodeList nList2 = eElement1.getElementsByTagName("field");
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Node nNode2 = nList2.item(temp2);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
String value1=null;
String value2=null;
if(eElement2.getAttribute("name").equalsIgnoreCase("value"))
{
valueList.add(eElement2.getTextContent());
// System.out.println(" Title value :: "+eElement2.getTextContent());
}
if(eElement2.getAttribute("name").equalsIgnoreCase("CID") && !(eElement2.getTextContent().equals("NULL")))
{
// System.out.println(" XXXXXXXXXXX Title value :: "+eElement2.getTextContent());
cidList.add(eElement2.getTextContent());
}
}
}
}
}
}
}
}
for(int i=0;i<valueList.size();i++)
{
System.out.println("value :: "+ valueList.get(i)+" corresponding cid :: "+ cidList.get(i));
//System.out.println("cid :: "+ cidList.get(i));
}
}
catch (Exception e) {
e.printStackTrace();
}
}}

I just want to point out where your mistake is. This is your original code.
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
if(eElement2.getAttribute("name").equalsIgnoreCase("value")){
titlevalue=eElement2.getTextContent();
}
if(eElement2.getAttribute("name").equalsIgnoreCase("CID") && (eElement2.getTextContent().equals(String.valueOf(301)))) {
System.out.println(" Title value :: "+titlevalue);
}
}
<row>
<field name="CID">201</field>
<field name="name">page_title</field>
<field name="value">Spotlight</field>
</row>
<row>
<field name="CID">301</field>
<field name="name">page_title</field>
<field name="value">Oryx highlights</field>
</row>
The order of the values of name attribute are CID, name and value. In the end of first loop of row tag, you will set titlevalue = Spotlight. Then in the beginning of second loop of row tag, you will skip the first if as the first field attribute is equal to CID. But the program will enter the second if because you define name=CID and the content=301, hence it displays titlevalue = Spotlight.
Try this.
Element eElement1 = (Element) nNode1;
NodeList nList2 = eElement1.getElementsByTagName("field");
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Node nNode2 = nList2.item(temp2);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
String nameattr = eElement2.getAttribute("name");
if (nameattr.equalsIgnoreCase("CID")) {
titlevalue = eElement2.getTextContent();
// If CID != 301, skip the whole loop.
if (!titlevalue.equalsIgnoreCase("301")) {
break;
}
}
else if (nameattr.equalsIgnoreCase("value")) {
System.out.println("value: " + eElement2.getTextContent());
}
}
}

Related

Java DOM Parser reading xml files information - nodes attributes

I have got an xml file and try to read in some information and try to arrange them.
The data in the xml looks like:
<Class code="1-10" kind="category">
<Meta name="P17b-d" value="2"/>
<SuperClass code="1-10...1-10"/>
<SubClass code="1-100"/>
<Rubric kind="preferred">
<Label xml:lang="de" xml:space="default">Klinische Untersuchung</Label>
</Rubric>
</Class>
and my Java class looks like:
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class Importer {
public static void main(String[] args) {
try {
File inputFile = new File("ops2022.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Class");
for (int temp = 0; temp < 10; temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName() );
Element iElement = (Element) nNode;
if (nNode.getNodeType() == Node.ELEMENT_NODE && iElement.getAttribute("kind").equals("category") ) {
Element eElement = (Element) nNode;
System.out.println("code : "
+ eElement.getAttribute("code"));
System.out.println("Label : "
+ eElement
.getElementsByTagName("Label")
.item(0)
.getTextContent());
System.out.println("SuperClass : "
+ eElement
.getElementsByTagName("SuperClass")
//I don't know how to get the attribute code here
);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
But how do I get the attribute's information of the "SuperClass" Node? Idon't know why but java handles eElement.getAttributeNode("SuperClass") as a node, although it is an Element. So I can't use the getAttribute().
I added the code in your answer (#Hiran Chaudhuri) to get my needed information:
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class Importer {
public static void main(String[] args) {
try {
File inputFile = new File("ops2022.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Class");
for (int temp = 0; temp < 10; temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName() );
Element iElement = (Element) nNode;
if (nNode.getNodeType() == Node.ELEMENT_NODE && iElement.getAttribute("kind").equals("category") ) {
Element eElement = (Element) nNode;
System.out.println("code : "
+ eElement.getAttribute("code"));
System.out.println("Label : "
+ eElement
.getElementsByTagName("Label")
.item(0)
.getTextContent());
System.out.println("SuperClass : "
+ eElement
.getElementsByTagName("SuperClass")
Node n = eElement.getElementsByTagName("SuperClass").item(0);
if (n instanceof Attr) {
Attr a = (Attr)n;
System.out.println(a.getName());
System.out.println(a.getValue());
}
);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
And I get the following
----------------------------
Current Element :Class
Current Element :Class
Current Element :Class
code : 1-10
Label : Klinische Untersuchung
and if I add another else clause like
else {
Attr a = (Attr)n;
System.out.println(a.getValue());
}
java throws the following error:
java.lang.ClassCastException: class com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to class org.w3c.dom.Attr (com.sun.org.apache.xerces.internal.dom.DeferredElementImpl and org.w3c.dom.Attr are in module java.xml of loader 'bootstrap')
at Importer.main(Importer.java:46)
.
With Element.getAttributeNode() you do receive a subclass/subinterface of Node called Attr. This Attr has getName() and getValue() methods that you should be interested in.
Using Element.getAttribute() will directly deliver the value of the corresponding attribute.
If you lost the chance to directly obtain the correct type, you can still recover like
Node n = ... // this is the attribute you are interested in
if (n instanceof Attr) {
Attr a = (Attr)n;
System.out.println(a.getName());
System.out.println(a.getValue());
}
So you are wondering how to access the SuperClass' code attribute. This code prints exactly the one value:
Document doc = dBuilder.parse(inputFile);
NodeList nList = doc.getElementsByTagName("Class"); // this list only contains Element nodes
for (int temp = 0; temp < nList.getLength(); temp++) {
Element nNode = (Element)nList.item(temp); // this is one 'class' element
NodeList nList2 = nNode.getElementsByTagName("SuperClass"); // this list only contains Element nodes
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Element superclass = (Element)nList2.item(temp2);
String code = superclass.getAttribute("code");
System.out.println(code);
}
}
However this code does the same:
Document doc = dBuilder.parse(inputFile);
XPath xpath = XPathFactory.newInstance().newXPath();
String code = xpath.evaluate("/Class/SuperClass/#code", doc);
With XPath expressions you can navigate the DOM tree much more efficiently.
The following code did the job for me:
for (int i = 0; i < nList.getLength(); i++) {
//for (int i = 0; i < 20; i++) {
Node nNode = nList.item(i);
//System.out.println("\nCurrent Element :" + nNode.getNodeName() );
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String supString = "OPS-2022";
NodeList fieldNodes = eElement.getElementsByTagName("SuperClass");
for(int j = 0; j < fieldNodes.getLength(); j++) {
Node fieldNode = fieldNodes.item(j);
NamedNodeMap attributes = fieldNode.getAttributes();
Node attr = attributes.getNamedItem("code");
if(attr != null) {
supString =attr.getTextContent();
}
}
}
}
Thanks for your help!

Difficulty in parsing xml using DOM Parser

How to get the values of the name tag which is nested under the grouped tag below. I am able to get the values of the name nested under column tag. How to get the nested values of name coming under grouped tag.The attributes of name tag coming under grouped tag is different.
<Services>
<Service name="check" regrx="" reverseExtention="" >
<File rootProfile="Test" extension="txt" seperator="," targetSeperator="q12">
<Columns>
<name id="1" usn="2234" dob="030395" age="55" validity="20" />
<name id="2" usn="I_TWO" dob="true" age="10" validity="44" >
<grouped>
<name id="343" value1="TYPE0" value2="TYPE4" type="" value7="1"></name>
<name id="564" value1="TYPE6" value2="TYPE7" type="" value7="0"></name>
</grouped>
</name>
<name id="3" usn="55453" dob="050584" age="35" validity="123"/>
<name id="5" usn="7565" dob="050488" age="44" validity="55"/>
</Columns>
</File>
</Service>
</Services>
Here is my code below
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
File fXmlFile = new File("D://test3.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodeList0 = doc.getElementsByTagName("Service");
NodeList nodeList1 = doc.getElementsByTagName("File");
NodeList nodeList2 = doc.getElementsByTagName("name");
NodeList nodeList3= doc.getElementsByTagName("grouped");
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
Node node0 = nodeList0.item(temp0);
System.out.println("\nElement type :" + node0.getNodeName());
Element Service = (Element) node0;
System.out.println("----" + temp0 + "-------");
if (node0.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("Name : " + Service.getAttribute("name"));
System.out.println("regrx : " + Service.getAttribute("regrx"));
System.out.println("reverex"+Service.getAttribute("reverseExtention"));
for (int temp = 0; temp < nodeList1.getLength(); temp++) {
Node node1 = nodeList1.item(temp);
System.out.println("------file" + temp + "--------");
System.out.println("\nElement type :" + node1.getNodeName());
Element File = (Element) node1;
//used for getting file level
if (node1.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("rootProfile:" + File.getAttribute("rootProfile"));
System.out.println("extension : " + File.getAttribute("extension"));
System.out.println("seperator : " + File.getAttribute("seperator"));
System.out.println("targetSeperator : " + File.getAttribute("targetSeperator"));
for(int temp2=0;temp2<nodeList2.getLength();temp2++){
Node node2 = nodeList2.item(temp2);
Element name = (Element) node2;
if (node2.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("id:" + name.getAttribute("id"));
System.out.println("usn : " + name.getAttribute("usn"));
System.out.println("dob : " + name.getAttribute("dob"));
System.out.println("age : " + name.getAttribute("age"));
System.out.println("validity : " + name.getAttribute("validity"));
//to get grouped node, the problem seems to be here
Node node3=nodeList3.item(temp2);
if(node3.hasChildNodes()){
Element grouped=(Element)node3;
if(node3.getNodeType()==Node.ELEMENT_NODE){
System.out.println("id:" + grouped.getAttribute("id"));
System.out.println("value1:" + grouped.getAttribute("value1"));
System.out.println("value2:" + grouped.getAttribute("value2"));
System.out.println("type:" + grouped.getAttribute("type"));
System.out.println("value7:" + grouped.getAttribute("value7"));
}
}
}
}
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
Below is your modified code
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File fXmlFile = new File("D://test3.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodeList0 = doc.getElementsByTagName("Service");
NodeList nodeList1 = doc.getElementsByTagName("File");
NodeList nodeList2 = doc.getElementsByTagName("name");
NodeList nodeList3 = doc.getElementsByTagName("grouped");
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
Node node0 = nodeList0.item(temp0);
System.out.println("\nElement type :" + node0.getNodeName());
Element Service = (Element) node0;
System.out.println("----" + temp0 + "-------");
if (node0.getNodeType() == Node.ELEMENT_NODE) {
System.out
.println("Name : " + Service.getAttribute("name"));
System.out.println("regrx : "
+ Service.getAttribute("regrx"));
System.out.println("reverex"
+ Service.getAttribute("reverseExtention"));
for (int temp = 0; temp < nodeList1.getLength(); temp++) {
Node node1 = nodeList1.item(temp);
System.out.println("------file" + temp + "--------");
System.out.println("\nElement type :"
+ node1.getNodeName());
Element File = (Element) node1;
// used for getting file level
if (node1.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("rootProfile:"
+ File.getAttribute("rootProfile"));
System.out.println("extension : "
+ File.getAttribute("extension"));
System.out.println("seperator : "
+ File.getAttribute("seperator"));
System.out.println("targetSeperator : "
+ File.getAttribute("targetSeperator"));
for (int temp2 = 0; temp2 < nodeList2.getLength(); temp2++) {
Node node2 = nodeList2.item(temp2);
Element name = (Element) node2;
if (node2.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("id:"
+ name.getAttribute("id"));
System.out.println("usn : "
+ name.getAttribute("usn"));
System.out.println("dob : "
+ name.getAttribute("dob"));
System.out.println("age : "
+ name.getAttribute("age"));
System.out.println("validity : "
+ name.getAttribute("validity"));
// to get grouped node, the problem seems to
// be here
// Node node3 = nodeList3.item(temp2);
NodeList grouped = node2.getChildNodes();
if (grouped != null
&& grouped.getLength() > 0) {
for (int ii = 0; ii < grouped
.getLength(); ii++) {
Node group = grouped.item(ii);
{
NodeList gropedNames = group
.getChildNodes();
if (gropedNames != null
&& gropedNames
.getLength() > 0) {
for (int jj = 0; jj < gropedNames
.getLength(); jj++) {
if (gropedNames
.item(jj) != null
&& gropedNames
.item(jj)
.getAttributes() != null) {
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"id"));
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"value1"));
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"value2"));
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"value7"));
}
}
}
}
}
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you need the nested name tags under the grouped, then ask the elements from the grouped tag and not from the document.
Document.getElementsByTagName() gives you back all tags by that name, calling getElementsByTagName() on an Element will give you back all the descendant elements of the Elemenent (e.g. child, grandchild etc.).
You can safely cast the grouped Node to Element and call getElementsByTagName() on it:
NodeList groupedNodeList = doc.getElementsByTagName("grouped");
for (int i = 0; i < groupedNodeList .getLength(); i++) {
Element groupedElement = (Element) groupedNodeList .item(i);
NodeList nameList = groupedElement.getElementsByTagName("name");
// Here you go, you have the list of name tags UNDER grouped
// Printing the id and value attributes of the name tag:
for (int j = 0; j < nameList.getLength(); j++) {
Element name = (Element) nameList.item(j);
System.out.println("Found <name>: id=" + name.getAttribute("id"));
System.out.println("\tvalue1=" + name.getAttribute("value1"));
System.out.println("\tvalue2=" + name.getAttribute("value2"));
System.out.println("\tvalue7=" + name.getAttribute("value7"));
}
}
Output is:
Found <name>: id=343
value1=TYPE0
value2=TYPE4
value7=1
Found <name>: id=564
value1=TYPE6
value2=TYPE7
value7=0

Possible way to parse the text alone from an xml document using java dom

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.

How to read alternative tags in xml using java?

I have xml file
<A>
<A1>
<A2>Hi</A2>
</A1>
<A>
<B>
<B1></B1>
<B2>100</B2>
</B>
<A>
<A1>
<A2>Hello</A2>
</A1>
<A>
<B>
<B1>1000</B1>
<B2></B2>
</B>
likewise this goes more than 10 blocks. Now my java code able to read one by one that is first reads all after that reads tag.
Code:
public class XMLParse {
static Document doc;
public static void main(String argv[]) {
try {
File file = new File("/home/dev042/Desktop/xxx.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("A");
System.out.println("Information of all Balence Sheet");
int count = nodeLst.getLength();
String name;
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("A1");
for(int i =0; i < fstNmElmntLst.getLength(); i++ )
{
Node lst = fstNmElmntLst.item(i);
if(lst.getNodeType() == Node.ELEMENT_NODE)
{
Element fsttravel = (Element) lst;
NodeList secNmElt = fsttravel.getElementsByTagName("*");
name = secNmElt.item(0).getTextContent();
System.out.println("Name : " + name);
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
String amt;
double amount;
NodeList nodeLst = doc.getElementsByTagName("B");
int coun = nodeLst.getLength();
for (int s = 0; s < nodeLst.getLength(); s++) {
Node secNode = nodeLst.item(s);
if (secNode.getNodeType() == Node.ELEMENT_NODE) {
try
{
Element amtval = (Element) secNode;
NodeList secval = amtval.getElementsByTagName("B1");
amt = secval.item(0).getTextContent();
//amount = Double.parseDouble(amt);
System.out.println("SubAmt :" + amt);
NodeList lstNmElmntLst = amtval.getElementsByTagName("B2");
amt = lstNmElmntLst.item(0).getTextContent();
System.out.println("MainAmt : " +amt);
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}
current output:
Hi
Hello
100
1000
I want to read the tags alternatively. then only i can able map the values. How can i read these tags alternatively. output should be like this
Hi 100
Hello 1000
Kindly help me out of it.
Thanks in advance..
I think you need to filter only tags so that your parser will fetch only tags.For this you can use XPath.This is an examples here:
http://www.roseindia.net/tutorials/xPath/java-xpath.shtml

Reading contents of the XML using java

I'm trying to read an XML file using java. I can sucessfully read the file but the problem is, I don't know how to read the values inside the column tag.
Since the column tags are not unique, I have no idea how to read them. Can someone help me.
Thanks in advance.
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
public static void main(String argv[]) {
try {
//new code
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL("http://www.cse.lk/listedcompanies/overview.htm?d-16544-e=3&6578706f7274=1").openStream());
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("row");
System.out.println("Information of all Stocks");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
//NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("column");
//Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
//NodeList fstNm = fstNmElmnt.getChildNodes();
//System.out.println("First Tag : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("column");
// Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
for (int columnIndex = 0; columnIndex < lstNmElmntLst.getLength(); columnIndex++) {
Element lstNmElmnt = (Element) lstNmElmntLst.item(columnIndex);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Tag : " + ((Node) lstNm.item(0)).getNodeValue());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code :
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("column");
Return a List of column nodes, why not just use a for loop to iterate over them all instead of just reading the first one ?
for (int columnIndex = 0; columnIndex < fstNmElmntLst.getLength(); columnIndex++) {
Element fstNmElmnt = (Element) fstNmElmntLst.item(columnIndex);
...
}
You now get a NPE on:
<column/>
and you should check your list size before getting element 0:
NodeList lstNm = lstNmElmnt.getChildNodes();
if (lstNm.getLength() > 0) {
System.out.println("Last Tag : " + ((Node)lstNm.item(0)).getNodeValue());
} else {
System.out.println("No content");
}
And as you're processing text content in nodes, have a look at the answer to this SO question. Text nodes are irriting as:
<foo>
a
b
c
</foo>
can be or are more than one child node of foo, and getTextContent() can ease the pain a bit.

Categories