<taxmann>
<docdetails>
<info id="104010000000007617" date="19780225">
<physicalpath>\\192.168.1.102\CMS\DATA</physicalpath>
<filepath isxml="N">
\NOTIFICATIONS\DIRECTTAXLAWS\HTMLFILES\150025021978.htm
</filepath>
<summary></summary>
<description></description>
<heading>
2187 [S.O.1500] | Section 35(1)(ii) of the Income-tax Act, 1961 - Scientific research expenditure - Approved scientific research associations/institutions
</heading>
<correspondingcitation/>
<hasfile>YES</hasfile>
<sortby>20120328160152743</sortby>
<parentid></parentid>
<parentchapterid></parentchapterid>
</info>
</docdetails>
</taxmann>
Code:
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_DOCDETAILS);
// 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);
map.put(KEY_HEADING, parser.getValue(e, KEY_HEADING));
// adding HashList to ArrayList
menuItems.add(map);
}
This is My Xml Format i want to xmlParse and want to dsiaply id,date,heading i m able to display heading But i am not to print date and id can u please tell me how i will implemnt it . this is my code to Print heading please modify my code and Print heading ,id,date..
1.Declaration
String URL = "http://www.google.co.in/ig/api?news&hl=en";
String KEY_ITEM = "news";
String KEY_ID = "news_entry";
String KEY_NAME = "title";
String KEY_COST = "url";
String KEY_DESC = "snippet";
2.Parsing
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);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
System.out.println("attrlength"+attributes.getLength());
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
// menuItems.add(map);
}
NodeList nl = doc.getElementsByTagName("info");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
Related
I'm iterating an XML object, but its fetching only one XML tag value. Please check the code. It is printing only the first tag value "abd5fd81-2bd6-4479-9d60-61fe533a13b7".
public class sample {
/**
* #param args
*/
private final static String XML_DATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<list>" +
"<string>abd5fd81-2bd6-4479-9d60-61fe533a13b7</string>" +
"<string>e127393b-343b-433c-87fc-27289758cca8</string>" +
"<string>753f79fe-a1d2-4383-b5c9-3ec8aa6b7e65</string>" +
"<string>2c71f819-65a6-4b08-8870-e71b1c770992</string>" +
"<string>ad22d8c0-8187-4243-8189-92e94c969208</string>" +
"<string>e6e70ab9-6149-4dfd-9d88-e27ec419847e</string>" +
"<string>87d8566b-4c8a-4ef0-9fa9-c7b8805e5631</string>" +
"<string>1309a729-20b4-40bb-96c8-46c96f205e60</string>" +
"<string>5e78b822-d472-4f02-859d-de36183c5d01</string>" +
"<string>410c70fb-8b05-47ef-bfbf-29284e45c8d3</string>" +
"</list>";
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
// TODO Auto-generated method stub
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XML_DATA));
Document doc = builder.parse(is);
NodeList nodes = doc.getElementsByTagName("list");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("string");
Element line = (Element) name.item(0);
System.out.println("String: " + getCharacterDataFromElement(line));
}
}
private static String getCharacterDataFromElement(Element e) {
// TODO Auto-generated method stub
Node child = e.getFirstChild();
if (child instanceof org.w3c.dom.CharacterData) {
org.w3c.dom.CharacterData cd = (org.w3c.dom.CharacterData) child;
return cd.getData();
}
return "?";
}
}
Is there anything missing in the code?
Because I don't have a compiler ready right now, I do not know for sure if this is perfect. Try it and report back:
....
Document doc = builder.parse(is);
NodeList nodes = doc.getElementsByTagName("list");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("string");
for (int x = 0; x < name.getLength(); x++) {
Element line = (Element) name.item(x);
System.out.println("String: " + getCharacterDataFromElement(line));
}
}
....
I think that should be what you are after.
You're reading just first string:
NodeList name = element.getElementsByTagName("string");
Element line = (Element) name.item(0); ### LOOP INSTEAD OF GETTING item(0)
To read all of them you have to loop over all nodes from name, similarly what you did in outer for loop:
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("string");
for (int j = 0; j < name.getLength(); j++) {
Element line = (Element) name.item(j);
System.out.println("String: " + getCharacterDataFromElement(line));
}
}
I'm facing a problem with XML parsing with Java dom.
I have the following XML
<XXX>AA</XXX>
<YYY>BB</YYY>
<Params>
<Param>
<ParamID>10</ParamID>
<value>
<val1>1</val1>
<val2>2</val2>
<val3>3</val3>
</value>
</Param>
<Param>
<ParamID>20</ParamID>
<value>
<val1>4</val1>
<val2>5</val2>
<val3>6</val3>
</value>
</Param>
</Params>
I have this java code
String targetNodeName = "Params";
NodeList nodes = getParents(xmlString, targetNodeName);
for (int i = 0 ; i < nodes.getLength() ; i++){
Element currentElement = nodes.item(i);
NodeList fields = currentElement.getChildNodes();
for (int j = 0 ; j < fields.getLength() ; j++){
Node currentFieldElement = fields.item(j);
if (currentFieldElement != null && currentFieldElement.getNodeType() == Node.ELEMENT_NODE) {
String key = currentFieldElement.getNodeName();
String value = currentFieldElement.getTextContent();
Hashtable.put(key, value);
}
}
private static NodeList getParents (String xmlString, String tagName) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse( new InputSource( new StringReader( xmlString ) ) );
return document.getElementsByTagName(tagName);
}
The problem is that I want to have the result as a map (hashmap for example) with the pair
Example :
{ <XXX, [AA] > , <YYY, [BB] > , <10, [1 , 2 , 3] > ....}
How can I do this approach ?
Thank you
NodeList nodes = getParents(getTestingResponse(), targetNodeName);
HashMap<Integer, Object> hm = new HashMap<Integer, Object>();
for (int i = 0 ; i < nodes.getLength() ; i++){
Element currentElement = (Element) nodes.item(i);
NodeList fields = currentElement.getChildNodes();
for (int j = 0 ; j < fields.getLength() ; j++){
Node currentFieldElement = fields.item(j);
List<Integer> integer = new ArrayList<Integer>();
List<Integer> integerNew = new ArrayList<Integer>();
if (currentFieldElement != null && currentFieldElement.getNodeType() == Node.ELEMENT_NODE) {
String key = currentFieldElement.getNodeName();
String[] value = currentFieldElement.getTextContent().split("\n");
for (String v : value) {
System.out.println(v);
try {
integer.add(Integer.parseInt(v.trim()));
} catch(Exception e) {}
}
integerNew.add(integer.get(1));
integerNew.add(integer.get(2));
integerNew.add(integer.get(3));
hm.put(integer.get(0), integerNew);
}
}
}
System.out.println(hm);
Or otherwise, you can try this following code:
try
{
// File inputFile = new File("Input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(DomParserPuCm.class.getResourceAsStream("Input.xml"));
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList params = doc.getElementsByTagName("Params");
HashMap<Integer, Object> paramsHM = new HashMap<Integer, Object>();
System.out.println(params.getLength());
for (int p = 0; p < params.getLength(); p++) {
NodeList param = params.item(p).getChildNodes();
if (param.item(p).getLocalName() != null) {
for (int z = 0; z < param.getLength(); z++) {
System.out.println(param.item(z).getLocalName());
if(param.item(z).getLocalName().equals("Param")) {
NodeList children = param.item(z).getChildNodes();
for (int c = 0; c < children.getLength(); c++) {
int paramID = 0;
int value1 = 0;
int value2 = 0;
int value3 = 0;
List<Integer> valueList = new ArrayList<Integer>();
if (children.item(c).getLocalName() != null) {
if (children.item(c).getLocalName().equals("ParamID")) {
try{paramID = Integer.parseInt(children.item(c).getFirstChild().getNodeValue());}catch(Exception e){}
} else if (children.item(c).getLocalName().equals("value")) {
NodeList values = children.item(c).getChildNodes();
try{value1 = Integer.parseInt(values.item(0).getFirstChild().getNodeValue());}catch(Exception e){}
try{value2 = Integer.parseInt(values.item(1).getFirstChild().getNodeValue());}catch(Exception e){}
try{value3 = Integer.parseInt(values.item(2).getFirstChild().getNodeValue());}catch(Exception e){}
valueList.add(value1);
valueList.add(value2);
valueList.add(value3);
}
}
System.out.print(valueList);
paramsHM.put(paramID, valueList);
}
}
}
}
}
System.out.print(paramsHM);
}
catch (Exception e)
{
e.printStackTrace();
}
I have two different XML's, both containing the same products but in another language.
The problem is, I want to add the description of the French XML to the description of the Dutch one, but the French XML contains a lot more products.
This is what I tried, but it doesn't work since the French XML is bigger. (Also, I believe I made a mistake since the products aren't on the same position either, they just share the same product code (named code in the Dutch XML and artikelnummer in the French XML).
What should I do here?
doc = (Document) builder.build(xmlFile);
docfrans = (Document) builder.build(xmlFilefrans);
root = doc.getRootElement();
root.setName("productlist");
List<Element> elementje = root.getChildren();
rootfrans = docfrans.getRootElement();
List<Element> elementjefrans = rootfrans.getChildren();
for (int i = 0; i < elementjefrans.size(); i++) {
Element verwijderdelementfrans = elementjefrans.get(i);
Element verwijderdelement = elementje.get(i);
List<Element> lijstjefrans = verwijderdelementfrans.getChildren();
List<Element> lijstje = verwijderdelement.getChildren();
for (int j = 0; j < lijstjefrans.size(); j++) {
if ( verwijderdelementfrans.getChild("artikelnummer").getText().equals(verwijderdelement.getChild("code").getText()) ){
System.out.println("test");
verwijderdelement.getChild("description").setText(verwijderdelement.getChild("description").getText()+verwijderdelementfrans.getChild("omschrijving").getText());
}
}
}
Figured it out myself after a lot of searching, for those interested :
SAXBuilder builder = new SAXBuilder();
String eol = System.getProperty("line.separator");
doc = (Document) builder.build(xmlFile);
docfrans = (Document) builder.build(xmlFilefrans);
root = doc.getRootElement();
root.setName("productlist");
List<Element> elementje = root.getChildren();
rootfrans = docfrans.getRootElement();
List<Element> elementjefrans = rootfrans.getChildren();
for (int i = 0; i < elementjefrans.size(); i++) {
for (int k = 0; k < elementje.size(); k++) {
Element verwijderdelementfrans = elementjefrans.get(i);
Element verwijderdelement = elementje.get(k);
// for (int j = 0; j < lijstje.size(); j++) {
if (verwijderdelementfrans.getChild("artikelnummer").getText().equals(verwijderdelement.getChild("code").getText())) {
System.out.println("test");
verwijderdelement.getChild("description").setText(verwijderdelement.getChild("description").getText() +"\n"+"\n"+ verwijderdelementfrans.getChild("omschrijving").getText());
}
// }
}
}
Hi i want to parse XML and display list based on selection of user
my xml is looking like this
below is my code
try {
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("company");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
// creating new HashMap
Element e = (Element) n1.item(i);
System.out.println("name node "+parser.getValue(e, "name"));
}
by this way i am getting the output like
Company ABC
Company XYZ
of Companies list
but
i would write code like
NodeList n1 = doc.getElementsByTagName("province");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
// creating new HashMap
Element e = (Element) n1.item(i);
System.out.println("name node "+parser.getValue(e, "name"));
}
i am getting list of province name
Alberta
Ontario
New York
Florida
but it should work like this
when i select Company ABC
only two provision list should display
Alberta
Ontario
not should all display can any body help me how to rewrite my code
This should do it:
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("company");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
Element e = (Element) n1.item(i);
System.out.println("name node " +parser.getValue(e, "name"));
NodeList children = e.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeName().equalsIgnoreCase("province")) {
System.out.println("name node " + parser.getValue((Element)child, "name"));
}
}
}
Use Node.getChildNodes() over the "company" nodes. Then, to get the child province nodes, compare by name. Example:
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("company");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
Node companyNode = n1.item(i);
NodeList childNodes = companyNode.getChildNodes();
// Here we're getting child nodes inside the company node.
// Only direct childs will be returned (name and province)
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
if("province".equalsIgnoreCase(childNode.getName())){
//Do something with province
}
}
}
Try the following code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
URL url = new URL(
"http://xyz.com/aa.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
/** Assign textview array lenght by arraylist size */
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Set the layout view to display */
setContentView(layout);
}
}
The getElementsBytagName called on the document object will always return the list of all the nodes with the given tag name in the whole document. Instead, filter out the single company element you are interested in, and then call getElementsByTagName on it. E.g.
Element companyEl = doc.getElementById(desiredCompanyId);
if (companyEl != null) { // always good to check
NodeList n1 = companyEl.getElementsByTagName("province");
// your code here
}
Try with this code
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
I have the xml file as follows,
<CHPkt xmlns="Smartscript/EmarSchema">
<CHInfo>
<StoreId>1800</StoreId>
<CHId>DB439A79-3D6F-4D25-BE0A-C4692978C072</CHId>
<CHName>Test</CHName>
<Address>
<Address1>Test Address</Address1>
</Address>
<DrugRounds>
<RoundTime>09:00</RoundTime>
<RoundTime>13:00</RoundTime>
<RoundTime>17:00</RoundTime>
</DrugRounds>
</CHInfo>
</CHPkt>
How to get the values of the tags which has the same name, my code is as follows,
public class ReadXml {
public static void main(String[] args){
try{
File xmlFile = new File("/home/jayakumar/Desktop/SmartScript.XML");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
NodeList nodeList1 = document.getElementsByTagName("CHInfo");
System.out.println("######################################");
for(int i =0;i<nodeList1.getLength();i++){
org.w3c.dom.Node node = nodeList1.item(i);
if(node.getNodeType()== org.w3c.dom.Node.ELEMENT_NODE){
Element element = (Element) node;
System.out.println("StoreId : " + getTagValue("StoreId", element));
System.out.println("CHId : " + getTagValue("CHId", element));
System.out.println("CHName : " + getTagValue("CHName", element));
System.out.println("Address : " + getTagValue("Address1", element));
}
NodeList nodeList2 = document.getElementsByTagName("DrugRounds");
System.out.println("-------------->"+"DrugRounds");
for(int j =0;j<nodeList2.getLength();j++){
org.w3c.dom.Node subNode = nodeList2 .item(j);
Element e = (Element) subNode;
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static String getTagValue(String sTag, Element element) {
NodeList nlList = element.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
I wasn't able to extract the values of second and third Roudtimes.How to parse the tags with same name
Thanks
Why not just check if it has any child nodes then get the value from it
for (int j = 0; j < nodeList2.getLength(); j++) {
org.w3c.dom.Node subNode = nodeList2.item(j);
NodeList childNodes = subNode.getChildNodes();
for(int iDx = 0; iDx < childNodes.getLength(); iDx++){
if(childNodes.item(iDx) instanceof Element){
Element e = (Element) childNodes.item(iDx);
System.out.println("RoundTime : "+ e.getFirstChild().getNodeValue());
}
}