1

这两天我一直在敲我的头。我有一个 XHTML 网页,我想从中删除一些数据,我正在使用 JTidy 到 DOMParse,然后 XPathFactory 使用 XPath 查找节点

Xhtml 片段是这样的

    <div style="line-height: 22px;" id="dvTitle" class="titlebtmbrdr01">BAJAJ AUTO LTD.</div>

现在我想要 BAJAJ AUTO LTD。

我正在使用的代码是:

    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Vector;

    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathExpression;
    import javax.xml.xpath.XPathExpressionException;
    import javax.xml.xpath.XPathFactory;

     import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;


   public class BSEQuotesExtractor implements valueExtractor {

@Override
public Vector<String> getName(Document d) throws XPathExpressionException {
    // TODO Auto-generated method stub
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//div[@id='dvTitle']/text()");
    Object result = expr.evaluate(d, XPathConstants.NODESET);
    NodeList nodes = (NodeList)result;
    for(int i=0;i<nodes.getLength();i++)
    {
        System.out.println(nodes.item(i).getNodeValue());
    }

    return null;
}

public static void main(String[] args) throws MalformedURLException, IOException, XPathExpressionException{
    BSEQuotesExtractor q = new BSEQuotesExtractor();
    DOMParser parser = new DOMParser(new URL("http://www.bseindia.com/bseplus/StockReach/StockQuote/Equity/BAJAJ%20AUTO%20LTD/BAJAJAUT/532977/Scrips").openStream());
    Document d = parser.getDocument();
    q.getName(d);

}

    }

但我得到一个空输出而不是 BAJAJ AUTO LTD。请救救我

4

2 回答 2

1

try this.

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//div[@id='dvTitle']");
Object result = expr.evaluate(d, XPathConstants.NODE);
Node node = (Node)result;
System.out.println(node.getTextContent());
于 2012-07-09T09:29:04.047 回答
1

您必须使用XPathConstants.STRING而不是XPathConstants.NODESET. 您想要获取单个元素 (div) 的值,而不是节点列表。写:

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String divContent = (String) path.evaluate("//div[@id='dvTitle']", document, XPathConstants.STRING);

进入divContent你得到“BAJAJ AUTO LTD.”。

于 2012-07-09T09:45:45.990 回答