在字符串问题中存储XPath查询xml

时间:2013-01-10 15:02:54

标签: java xml dom xpath

我遇到了存储使用DOM构建的字符串并使用xpath查询的问题。以下是我在代码GoogleSample

中使用的一些参考
public static String getRoute() throws Exception {
    String xPathString = "//text() ";
    String nodeString = "";
    String notags = null;

    XPathFactory factory = XPathFactory.newInstance();

    XPath xpath = factory.newXPath();

//URL and HTTP connection here



InputStream inputXml = connection.getInputStream();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(inputXml);

            NodeList nodes = (NodeList) xpath.evaluate(xPathString, doc, XPathConstants.NODESET);

            for (int i = 0, n = nodes.getLength(); i < n; i++) {

                nodeString = nodes.item(i).getTextContent();
                notags = nodeString.replaceAll("<[^>]*>", "");
                System.out.print(notags + "\n");

            } 
        } catch (XPathExpressionException ex) {
            System.out.print("XPath Error");
        }

        return notags;

代码似乎在try和catch块中打印出System.out.print(notags + "\n");,但是当我尝试获取方法并使用以下命令进行系统打印时:

public static void main (String[] args) {
     try {
      System.out.println(getRoute());  
    } catch (Exception e) {
        System.out.println(e);
    }
 }

我只能获得输出的最后一行而不是整个String。

1 个答案:

答案 0 :(得分:2)

我怀疑,在这一行:

notags = nodeString.replaceAll("<[^>]*>", "");

在循环的每次迭代期间,您完全覆盖notags。你需要这样做:

notags += nodeString.replaceAll("<[^>]*>", "");

在每一行之间添加换行符,您可以这样做:

notags += nodeString.replaceAll("<[^>]*>", "") + "\n";

并且为了使其中任何一个起作用,您还需要更改它:

String notags = null;

到此:

String notags = "";

你确定需要replaceAll()吗?我希望nodeString已经没有任何<>,因为您正在选择文本节点。