gpt4 book ai didi

java - 如何使用 DOM 获取 ElementById?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:47:09 25 4
gpt4 key购买 nike

我有下面给出的 HTML 页面的一部分,我想使用 DOM 解析器提取其 id 为 hiddenDivHL 的 div 标签的内容:

HTML 页面的一部分:

<div id='hiddenDivHL' style='display:none'>http://74.127.61.106/udayavaniIpad/details.php?home=0&catid=882&newsid=123069[InnerSep]http://www.udayavani.com/udayavani_cms/gall_content/2012/1/2012_1$thumbimg117_Jan_2012_000221787.jpg[InnerSep]ಯುವಜನತೆಯಿಂದ ಭವ್ಯಭಾರತ[OuterSep]

到目前为止,我已经使用了下面的代码,但我无法使用 getElementById。该怎么做?

DOM 解析器:

    try {

URL url = new URL("http://74.127.61.106/udayavaniIpad/details_android.php?home=1&catid=882&newsid=27593");
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);

Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("hiddenDivHL");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());


layout.addView(name[i]);



}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}

/** Set the layout view to display */
setContentView(layout);

}

最佳答案

XPath 是恕我直言,是在 Java 中导航 DOM 的最常见和最简单的方法。

try{
URL url = new URL("http://74.127.61.106/udayavaniIpad/details_android.php?home=1& catid=882&newsid=27593");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/item/div[@id='hiddenDivHL']";
Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);

} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}

我不确定 XPath 表达式是否正确,但链接在这里:http://developer.android.com/reference/javax/xml/xpath/package-summary.html

关于java - 如何使用 DOM 获取 ElementById?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893830/

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