https://nim-lang.org/docs/parsexml.html
文档仅介绍了使用 open
从文件字符串流进行解析,但是如果我只有一个纯字符串(例如 httpclient client.get body),我该怎么做。
最佳答案
为了将 parsexml
与内存中的字符串一起使用,您必须使用 streams module 从字符串创建流。 。 parsexml
模块嵌入了一个从文件中读取的示例,这些是您需要更改以使其从字符串中解析的行:
var filename = addFileExt(paramStr(1), "html")
let buffer = readFile(filename)
var s = newStringStream(buffer)
if s == nil: quit("cannot open the file " & filename)
完整的示例如下:
import os, streams, parsexml, strutils
if paramCount() < 1:
quit("Usage: htmltitle filename[.html]")
var filename = addFileExt(paramStr(1), "html")
let buffer = readFile(filename)
var s = newStringStream(buffer)
if s == nil: quit("cannot open the file " & filename)
var x: XmlParser
open(x, s, filename)
while true:
x.next()
case x.kind
of xmlElementStart:
if cmpIgnoreCase(x.elementName, "title") == 0:
var title = ""
x.next() # skip "<title>"
while x.kind == xmlCharData:
title.add(x.charData)
x.next()
if x.kind == xmlElementEnd and cmpIgnoreCase(x.elementName, "title") == 0:
echo("Title: " & title)
quit(0) # Success!
else:
echo(x.errorMsgExpected("/title"))
of xmlEof: break # end of file reached
else: discard # ignore other events
x.close()
quit("Could not determine title!")
关于xml - 使用标准模块 `parsexml` ,如何通过纯字符串流或字符串而不是文件解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354244/