5

我有一个格式为 XML 的文件:

<?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>

我的程序

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();}}}

输出:

id0 98500 Europe Ukraine Kiev Kiev 1

ia 如何获得 href 的值?需要输入什么代码来输出链接?

4

1 回答 1

1

将此代码添加到侧面 for 循环

  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"));
于 2013-03-01T10:53:14.480 回答