This is my xml format:
<taxmann>
<docdetails>
<info id="104010000000006516" date="20120120">
<physicalpath>\\192.168.1.102\CMS\DATA</physicalpath>
<filepath isxml="N">\CIRCULARS\DIRECTTAXLAWS\HTMLFILES\CIRDGBACDD4836150012011122012012.htm</filepath>
<summary></summary>
<description></description>
<heading>DGBA.CDD. NO.H- 4836 /15.02.001/2011-12 | Clarification on Regulation of Interest Rates for Small Savings Schemes</heading>
<correspondingcitation/>
<hasfile>YES</hasfile>
<sortby>20120328155728957</sortby>
<parentid></parentid>
<parentchapterid></parentchapterid>
</info>
</docdetails>
</taxmann>
I'm able to retrieve data of heading but I want to print date and id too but I'm not able to do this. Please tell me how to implement it.
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
String Heading= parser.getValue(e, KEY_NAME).replace("|", "|\n").replace("|", "");
map.put(KEY_NAME,Heading);
// adding HashList to ArrayList
menuItems.add(map);
}
This is my code please tell me the logic how I can parse, so that I can get date and id too.
Are you sure this is the easiest way to read that xml file? It just looks a bit too complicated. Why don't you navigate manually through the tree structure?
I would say you would get it this way:
SAXBuilder builder = new SAXBuilder();
Document doc;
doc = builder.build(file);
//rootElement would be your "taxmann" element
Element rootElement = doc.getRootElement();
Element docdetailsElement = rootElement.getChild("docdetails");
Element infoElement = docdetailsElement.getChild("info");
String id = infoElement.getAttributeValue("id");
String date = infoElement.getAttributeValue("date");
You should use Element#getAttribute(String name) method. In your case something like:
String id=e.getAttribute("id");
String date=e.getAttribute("date");
Related
Im trying to extract data from a database using xml tags but I keeping getting this error
'java.lang.String org.w3c.dom.Node.getNodeValue()' on a null object reference
Not sure why its saying the tag is null when I have a log of the string before I try to extracts the data and it looks like it should I believe.
<?xml version="1.0" ?>
<database>
<account>
<id>1</id>
<fname>john</fname>
<lname>smith</lname>
<status>1</status>
</account>
</database>
That is the output from the string which I'm trying to extract the data from and here is the code I'm using to extract it.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();;
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse (new ByteArrayInputStream(s.getBytes()));
Element docEle = dom.getDocumentElement ();
NodeList nl = docEle.getElementsByTagName("account");
Element entry = (Element)nl.item(0);
Element id = (Element)entry.getElementsByTagName("id").item(0);
Element fname= (Element)entry.getElementsByTagName("fname").item(0);
Element lname = (Element)entry.getElementsByTagName("lname").item(0);
Element status= (Element)entry.getElementsByTagName("status").item(0);
user_id = id.getFirstChild().getNodeValue();
user_fname = fname.getFirstChild().getNodeValue();
user_lname = lname.getFirstChild().getNodeValue();
user_status = status.getFirstChild().getNodeValue();
The app crashes when it try's to get the node value from the first element, any help Is appreciated and thanks in advance
You have started the <account> tag but did not end it. Change </user> to </account>
Managed to figure it out, and this would be helpful for anyone with similar issues i hope.
to be able to read the tag names from an xml string I did the following (s is the xml string variable)
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(s));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();;
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(is);
Element docEle = dom.getDocumentElement ();
NodeList nl = docEle.getChildNodes();
if (nl != null) {
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("account")) {
user_id = el.getElementsByTagName("id").item(0).getTextContent();
user_fname = el.getElementsByTagName("fname").item(0).getTextContent();
user_lname = el.getElementsByTagName("lname").item(0).getTextContent();
user_status = el.getElementsByTagName("status").item(0).getTextContent();
}
}
}
}
the user_ variables have the xml tag values
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
int displayPerPage = 5;
int TotalRows = xml.length();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
This is my Code i want to Count nUmber of node i m not able to do this please tell me how i will do it http://api.androidhive.info/pizza/?format=xml suppose this my xml contaion 10 item or Node how i will count please post me code for that
Just use nl.getLength(), it'll return you the number of items in each tag.
You can use something like
NodeList list = doc.getElementsByTagName("item");
System.out.println("Total of elements : " + list.getLength());
Take a look at this tutorial.
In my xml there can be empty tags like </title>.
The problem is that when I parse the xml, I am getting null pointer exception when I reach this line in the xml.
How should I check tags like this in my parsing file?
ArrayList<String>textcomment = new ArrayList<String>();
for(int i = 0;i<nl.getLength();i++)
{
Element e = (Element)nl.item(i);
// crash on this string find first time a value and second time find </no_of_comments>
String noOfcomment = e.getElementsByTagName("no_of_comments").item(0).getFirstChild ().getNodeValue();
aryNoOfcomment.add(i, noOfcomment);
}
What is the line with problem?
It's this line?
String noOfcomment = e.getElementsByTagName ("no_of_comments"). item (0). getFirstChild (). getNodeValue ();
You are getting everything in the same line, so you don't check if one of them was null.
You can separate and then check if the result is null, like this:
List<String> yourList = new ArrayList<String>();
NodeList nl = e.getElementsByTagName ("no_of_comments");
if(nl != null){
for(int i = 0;i<nl.getLength();i++)
{
Node n = nl.item(i).getFirstChild();
if(n!=null){
String value = n.getNodeValue();
yourList.add(value);
}
}
}
for parsing you can use this...
FileInputStream fi = new FileInputStream(dir);
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(fi);
NodeList nlorgid = doc.getElementsByTagName("Organization");
String orgidfromxml = ((Element)nlorgid.item(0)).getAttribute("id");
System.out.println(" organization id from xml is "+orgidfromxml);
I just started to try Jaxp13XPathTemplate but I'm a bit confused on parsing the XML.
Here is the sample XML
<fxDataSets>
<fxDataSet name="NAME_A">
<link rel="self" href="http://localhost:8080/linkA"/>
<baseCurrency>EUR</baseCurrency>
<description>TEST DESCRIPTION A</description>
</fxDataSet>
<fxDataSet name="NAME_B">
<link rel="self" href="http://localhost:8080/linkB"/>
<baseCurrency>EUR</baseCurrency>
<description>TEST DESCRIPTION B</description>
</fxDataSet>
<fxDataSets>
I'm already able to get NAME_A and NAME_B however I'm not able to get the description for both Node.
Here is what I have come up with.
XPathOperations xpathTemplate = new Jaxp13XPathTemplate();
String fxRateURL = "http://localhost:8080/rate/datasets";
RestTemplate restTemplate = new RestTemplate();
Source fxRate = restTemplate.getForObject(fxRateURL,Source.class);
List<Map<String, Object>> currencyList = xpathTemplate.evaluate("//fxDataSet", fxRate , new NodeMapper() {
public Object mapNode(Node node, int i) throws DOMException
{
Map<String, Object> singleFXMap = new HashMap<String, Object>();
Element fxDataSet = (Element) node;
String id = fxDataSet.getAttribute("name");
/* This part is not working
if(fxDataSet.hasChildNodes())
{
NodeList nodeList = fxDataSet.getChildNodes();
int length = nodeList.getLength();
for(int index=0;i<length;i++)
{
Node childNode = nodeList.item(index);
System.out.println("childNode name"+childNode.getLocalName()+":"+childNode.getNodeValue());
}
}*/
return new Object();
}
});
try to use dom4j library and it's saxReader.
InputStream is = FileUtils.class.getResourceAsStream("file.xml");
SAXReader reader = new SAXReader();
org.dom4j.Document doc = reader.read(is);
is.close();
Element content = doc.getRootElement(); //this will return the root element in your xml file
List<Element> methodEls = content.elements("element"); // this will retun List of all Elements with name "element"
Take a look public <T> List<T> evaluate(String expression, Source context, NodeMapper<T> nodeMapper)
evaluate takes NodeMapper<T> as one of its parameter
it returns object of type List<T>
But for your given code snippet:
its passing new NodeMapper() as parameter
but trying to return List<Map<String, Object>> which is surely violation of the contract of the api.
Probable solution:
I am assuming you wanna return a object of type FxDataSet which wraps <fxDataSet>...</fxDataSet> element. If this is the case,
pass parameter as new NodeMapper<FxDataSet>() as parameter
use List<FxDataSet> currencyList = ... as left hand side expression;
change method return type as public FxDataSet mapNode(Node node, int i) throws DOMException.
Take a look at the documentation also for NodeMapper.
Surely, I have not used Jaxp13XPathTemplate, but this should be common Java concept which helped me to find out what was wrong actually. I wish this solution will work.
If you want to get at the child nodes of the fxDataSet element you should be able to do:
Node descriptionNode= fxDataSet.getElementsByTagName("description").item(0);
I am trying to use a variable that specifies which parent.child nodes I am parsing.
below is my current xml:
<results>
<GW>
<result>
<item>Car</item>
<name>Bob</name
</result>
<result>
<item>Bike</item>
<name>Tom</name
</result>
</GW>
<BF>
<result>
<item>Apple</item>
<name>Mike</name
</result>
<result>
<item>Melon</item>
<name>Julia</name
</result>
</BF>
</results>
And here is my parsing code. I want to use the variable items to tell which node I am supposed to parse GW or BF
//DOC IS ASSIGNED THE XML DATA EARLIER IN THE CODE
Bundle bundle = getIntent().getExtras();
int ITEMS = bundle.getInt("selection");
NodeList nodes = doc.node[ITEMS].getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "item"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
I am trying to only parse either the child nodes of GW or BF and that depends on the value of ITEMS. So if items is equal to 0 then I would get the data from GW and if it is 1 I would get the data from BF.
If I could guess it would be something like:
NodeList nodes = doc.childNode[ITEMS].getElementsByTagName("result");
Element docElem = doc.getDocumentElement();
NodeList nl = docElem.getElementsByTagName("results");
Element elem = (Element)nl.item(ITEMS);
nodes = elem.getElementsByTagName("result");