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&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 ?
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With