Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get href value from XML file on java eclipse DOM

I have an XML file in the format:

<?xml version="1.0"?>

    <company>
    <tr>
    <td align="center" style="width:50px;">9850</td>
    <td align="center" style="width:150px;">Europe</td>
    <td align="center" style="width:150px;">Ukraine</td>
    <td align="center" style="width:100px;">Kiev</td>
    <td align="center"><a href="details.aspx?page=default&amp;post=99664">Kiev 1</a> </td> 
    </tr>
 </company>

My program

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;

import java.io.File;

public class Myversion { public static void main(String argv[])  {

        try { File myfile = new File("/Users/Nik/Downloads/1.xml");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    Document doc = dBuilder.parse(myfile);

    doc.getDocumentElement().normalize();

    NodeList nodeList = doc.getElementsByTagName(doc.getDocumentElement().getChildNodes().item(1).getNodeName());;

    for (int temp = 0; temp < nodeList.getLength(); temp++) {

    Node nNode = nodeList.item(temp);

    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

    Element element = (Element) nNode;

    System.out.print("id"+temp+" "+element.getElementsByTagName("td").item(0).getTextContent());
    System.out.print(" "+element.getElementsByTagName("td").item(1).getTextContent());
    System.out.print(" "+element.getElementsByTagName("td").item(2).getTextContent());
    System.out.print(" "+element.getElementsByTagName("td").item(3).getTextContent());
    System.out.print(" "+element.getElementsByTagName("td").item(4).getTextContent());

    }}} catch (Exception e) {e.printStackTrace();}}}

Output:

id0 98500 Europe Ukraine Kiev Kiev 1

How can ia get value of href ? What need to put in code to output link ?

like image 322
Sunny Avatar asked Nov 13 '22 10:11

Sunny


1 Answers

Add this code in side for loop

  Node href = element.getElementsByTagName("td").item(4);
    NodeList hrefList = href.getChildNodes();
    Element hrefEle = (Element)hrefList.item(0);
    System.out.println("href of "+ href.getTextContent() +"-->"+hrefEle.getAttribute("href"));
like image 198
NPKR Avatar answered Nov 15 '22 07:11

NPKR