-1

Web サイトからデータを取得してファイルに保存する Java コードを開発しています。xpath の結果をファイルに保存したい。xpath の出力を保存する方法はありますか? 間違いはご容赦ください。これは私の最初の質問です。

public class TestScrapping {

public static void main(String[] args) throws MalformedURLException, IOException, XPatherException {

    // URL to be fetched in the below url u can replace s=cantabil with company of ur choice
    String url_fetch = "http://www.yahoo.com";

    //create tagnode object to traverse XML using xpath
    TagNode node;
    String info = null;

    //XPath of the data to be fetched.....use firefox's firepath addon or use firebug to fetch the required XPath.
    //the below XPath will display the title of the company u have queried for
    String name_xpath = "//div[1]/div[2]/div[2]/div[1]/div/div/div/div/table/tbody/tr[1]/td[2]/text()";

     // declarations related to the api
    HtmlCleaner cleaner = new HtmlCleaner();
    CleanerProperties props = new CleanerProperties();
    props.setAllowHtmlInsideAttributes(true);
    props.setAllowMultiWordAttributes(true);
    props.setRecognizeUnicodeChars(true);
    props.setOmitComments(true);


    //creating url object
    URL url = new URL(url_fetch);
    URLConnection conn = url.openConnection(); //opening connection
    node = cleaner.clean(new InputStreamReader(conn.getInputStream()));//reading input stream

    //storing the nodes belonging to the given xpath
    Object[] info_nodes = node.evaluateXPath(name_xpath);
   // String li= node.getAttributeByName(name_xpath);


//checking if something returned or not....if XPath invalid info_nodes.length=0
    if (info_nodes.length > 0) {

        //info_nodes[0] will return string buffer
        StringBuffer str = new StringBuffer();
        {
            for(int i=0;i<info_nodes.length;i++)
                System.out.println(info_nodes[i]);
        }
        /*str.append(info_nodes[0]);
        System.out.println(str);
 */
     }

 }
 }
4

3 に答える 3

1

ノードを文字列としてコンソール/またはファイルに「単純に」出力できます-Perlの例:

my $all = $XML_OBJ->find('/');    # selecting all nodes from root
foreach my $node ($all->get_nodelist()) {
    print XML::XPath::XMLParser::as_string($node);
}

注: ただし、この出力は適切に xml 形式/インデントされていない可能性があります

于 2013-10-29T22:33:23.240 に答える
0

Node のコレクションである NodeSet を取得し、それを反復処理して、作成された DOM ドキュメント オブジェクトに追加することをお勧めします。
この後、TransformerFactory を使用しTransformer オブジェクトを取得し、その変換メソッドを使用できます。DOMSourceから、FileOutputStream に基づいて作成できるStreamResultオブジェクトに変換する必要があります。

于 2012-06-20T09:00:22.657 に答える
0

Java での XPath の出力はノードセットです。そのため、ノードセットを取得したら、それを使用して必要な処理を実行し、ファイルに保存して、さらに処理することができます。

それをファイルに保存するには、Javaでファイルに他のものを保存するのと同じ手順が必要です。それと他のデータとの間に違いはありません。ノードセットを選択し、それを繰り返し処理し、そこから必要な部分を取得して、ある種のファイル ストリームに書き込みます。

ただし、 Nodeset.SaveToFile() があるということであれば、いいえ。

于 2012-06-20T08:54:30.193 に答える