[英]Golang: Read single XML document from net.Conn
我有一個客戶端 - 服務器連接。 它們通過 xml 進行通信,並且在一個會話期間傳輸多個 xml 文檔。 xml.Unmarshal
希望字節片,但我不能只ReadAll
從插座的所有字節(它會嘗試更多然后一個XML,因此塊)。
是否有標准的 xml 解析器或庫,可以從字節流中解析並且讀取的數據不超過實際需要?
xml.Decoder
,您可以使用標准庫中的xml.Decoder
。 您可以使用xml.NewDecoder()
來創建一個新的xml.Decoder
,它需要一個io.Reader
從中讀取數據。 net.Conn
符合條件,因為它實現了io.Reader
。 Decoder.Decode()
方法將讀取和處理 1 個 XML 文檔。
讓我們看一個例子。 源將包含 2 個串聯的 XML 文檔,我們調用Decoder.Decode()
兩次以讀取和解析這 2 個文檔。
XML 源:2 個 XML 文檔(2 個<Person>
):
const data = `<Person>
<Name>Bob</Name>
<Age>23</Age>
</Person>
<Person>
<Name>Alice</Name>
<Age>21</Age>
</Person>
`
轉到 struct 來建模 XML 文檔:
type Person struct {
Name string
Age int
}
讀取這 2 個 XML 文檔的代碼:
buf := bytes.NewBuffer([]byte(data))
d := xml.NewDecoder(buf)
for i := 0; i < 2; i++ {
p := Person{}
if err := d.Decode(&p); err != nil {
fmt.Println(err)
} else {
fmt.Printf("%+v\n", p)
}
}
輸出(在Go Playground上試試):
{Name:Bob Age:23}
{Name:Alice Age:21}
請注意,如果沒有更多數據可用, Decoder.Decode()
將返回io.EOF
。 要從輸入中讀取所有 XML 文檔,您可以這樣做:
for {
p := Person{}
if err := d.Decode(&p); err != nil {
if err == io.EOF {
fmt.Println("EOF, breaking")
break
}
fmt.Println(err)
} else {
fmt.Printf("%+v\n", p)
}
}
如果要讀取通過 TCP 連接傳輸的 XML 文檔,只需將net.Conn
值(實現io.Reader
)傳遞給xml.NewDecoder()
:
var con net.Conn
// Initialize / obtain connection
d := xml.NewDecoder(con)
var doc YourDocType
if err := d.Decode(&doc); err != nil {
// Handle error
return
}
// No error, use doc:
fmt.Printf("%+v", doc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.