0

DOMで作成し、xpathで照会した文字列を保存する際に問題が発生します。これが私のコードGoogleサンプルで使用したいくつかのリファレンスです

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;

コードはSystem.out.print(notags + "\n");tryandcatchブロック内で出力されているようですが、メソッドを取得してシステムの印刷を実行しようとすると、次のようになります。

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

文字列全体ではなく、出力の最後の行しか取得できませんでした。

4

1 に答える 1

2

私が疑ったように、この行では:

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

notagsループのすべての反復中に完全に上書きされます。これを行う必要があります:

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

各行の間に改行を追加するには、次のようにします。

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

そして、それらのいずれかが機能するためには、これも変更する必要があります。

String notags = null;

これに:

String notags = "";

そのreplaceAll()が必要であると確信していますか?テキストノードを選択しているので、 nodeStringにはすでに<sまたはsがないことを期待します。>

于 2013-01-10T15:14:32.863 に答える