2012-06-20 22 views
-1

我正在開發的Java代碼從網站獲取數據,並將其存儲在一個文件中。我想將xpath的結果存儲到一個文件中。有什麼辦法可以保存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); 
*/ 
    } 

} 
} 
+0

什麼是[輸出](http://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/XPathConstants.html)的XPath表達式的? – McDowell

+0

@McDowell對象[] info_nodes = node.evaluateXPath(name_xpath); – prasad

+0

'evaluateXPath'不是標準的Java庫方法。說明你正在使用的庫。更詳細地更新您的問題。 – McDowell

回答

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格式/縮進

0

在Java中的XPath的輸出是一個節點集,所以是的,一旦你有一個節點集,你可以做你想做的事情什麼,將它保存到一個文件中,過程更是一番。

它保存到一個文件將涉及在Java中相同的步驟,節省了其他任何一個文件涉及,還有就是和任何其他數據沒有差別。選擇節點集,遍歷它,從它獲取你想要的部分,並將它們寫入某種文件流。

但是,如果你的意思是有一個Nodeset.SaveToFile(),則沒有。

0

我會建議你採取的節點集,這是節點的集合,重複它,並把它添加到創建的DOM文檔對象。
在此之後,你可以使用TransformerFactory得到一個Transformer對象,並使用它的變換方法。你應該從DOMSource轉化爲能夠將基於FileOutputStream中創建一個StreamResult對象。