gpt4 book ai didi

java - 如何从 java eclipse DOM 上的 XML 文件获取 href 值

转载 作者:数据小太阳 更新时间:2023-10-29 02:13:59 25 4
gpt4 key购买 nike

我有一个格式如下的 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 的值?输出链接需要写什么代码?

最佳答案

将这段代码添加到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"));

关于java - 如何从 java eclipse DOM 上的 XML 文件获取 href 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15155582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com