【问题标题】:Storing XPath query xml in string issue在字符串问题中存储 XPath 查询 xml
【发布时间】:2013-01-10 15:02:53
【问题描述】:

我在存储使用 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);
    }
 }

我只能得到输出的最后一行,而不是整个字符串。

【问题讨论】:

  • 你在哪里给notags赋值?看起来它在顶部被分配给 null 并保持这种状态。我也看不到在哪里定义了 inputXPath 或使用了 xPathString,但这可能是一个有争议的问题。
  • 对不起,我从测试类中粘贴了错误的代码。已编辑。

标签: java xml dom xpath


【解决方案1】:

正如我所怀疑的,在这一行中:

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

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

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

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

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

为了使其中任何一个工作,您还需要更改此设置:

String notags = null;

到这里:

String notags = "";

你确定 replaceAll() 是必要的吗?我希望 nodeString 已经没有任何 &lt;s 或 &gt;s,因为您正在选择文本节点。

【讨论】:

  • 由于某种原因,DOM 无法识别 标签,因为我在输出中获得了这些标签。哇,+(循环)使整个不同。我现在可以从中获得输出 :) 谢谢。还有 1 个问题,您如何为输出创建行,因为当前输出打印在一行中。再次感谢您的帮助。
  • 这很奇怪。也许 标签是文本值的一部分,而不是实际文本。无论如何,我已经修改了我的帖子来回答你的问题。
猜你喜欢
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2012-09-21
  • 2019-03-03
  • 1970-01-01
  • 2011-09-04
相关资源
最近更新 更多