2017-06-09 44 views
0

我想從套接字解析xml。我已經嘗試了很多使用clojure.xml/parse的例子,但沒有突破。下面是示例代碼,我開始與只讀取基於輸入文本:從套接字服務器讀取xml輸入clojure

(with-open [sock (Socket. host port) 
      reader (io/reader sock) 
      response (StringWriter.)] 
    (while (.isConnected sock) 
    (io/copy reader response) 
    (log/info response))) 
+0

您可以閱讀插座任何東西(文本字符串)?或者是在解析和xml字符串到clojure數據結構中的問題? –

+0

是的,我可以從套接字中讀取文本,但使用Xml這是我得到的:

+1

您的套接字設置中一定有錯誤。 XML只是字符串中的字符(如示例中的「xml-str」)。確保你可以傳輸字符串,如「你好」,「」「你好,」等等。一旦你可以將字符讀入一個字符串,然後可以解析它們。這是兩個不同的問題。 –

回答

0

這裏是doing it using Enlive一個辦法:

(ns tst.clj.core 
    (:use clj.core 
     tupelo.test) 
    (:require 
    [clojure.java.io :as io] 
    [net.cgrand.enlive-html :as en-html] 
    [tupelo.core :as t])) 
(t/refer-tupelo) 

; Discard any xml nodes of Type="A" or Type="B" (plus blank string nodes) 
(dotest 
    (let [xml-str  "<ROOT> 
         <Items> 
         <Item><Type>A</Type><Note>AA1</Note></Item> 
         <Item><Type>B</Type><Note>BB1</Note></Item> 
         <Item><Type>C</Type><Note>CC1</Note></Item> 
         <Item><Type>A</Type><Note>AA2</Note></Item> 
         </Items> 
        </ROOT>" 
     enlive-tree (->> xml-str 
         java.io.StringReader. 
         en-html/html-resource 
         first)] 
     (spyx-pretty enlive-tree))) 

與結果:

enlive-tree => 
{:tag :ROOT, 
:attrs nil, 
:content 
("\n      " 
    {:tag :Items, 
    :attrs nil, 
    :content 
    ("\n      " 
    {:tag :Item, 
    :attrs nil, 
    :content 
    ({:tag :Type, :attrs nil, :content ("A")} 
     {:tag :Note, :attrs nil, :content ("AA1")})} 
    "\n      " 
    {:tag :Item, 
    :attrs nil, 
    :content 
    ({:tag :Type, :attrs nil, :content ("B")} 
     {:tag :Note, :attrs nil, :content ("BB1")})} 
    "\n      " 
    {:tag :Item, 
    :attrs nil, 
    :content 
    ({:tag :Type, :attrs nil, :content ("C")} 
     {:tag :Note, :attrs nil, :content ("CC1")})} 
    "\n      " 
    {:tag :Item, 
    :attrs nil, 
    :content 
    ({:tag :Type, :attrs nil, :content ("A")} 
     {:tag :Note, :attrs nil, :content ("AA2")})} 
    "\n      ")} 
    "\n     ")} 
+0

你能分享一個套接字的例子嗎? –