Lua的XML提取模式

一个应用程序正在向我的脚本发送像这样的流:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <aRootChildNode>
    <anotherChildNode>
     <?xml version="1.0">
     <TheNodeImLookingFor>
       ... content ...
     </TheNodeImLookingFor>
    </anotherChildNode>
   </aRootChildNode>
</root>

我想提取TheNodeImLookingFor部分。 到目前为止,我已经得到了:

data = string.match(Stream, "^.+\<TheNodeImLookingFor\>.+\<\/TheNodeImLookingFor\>.+$")

模式被 Stream 识别,但它没有提取节点及其内容。

点赞
用户1009479
用户1009479

一般来说,不推荐使用模式匹配(无论是Lua模式还是正则表达式)来提取XML。应该使用XML解析器。

对于这个问题,你不需要转义 \<(即使你这样做,Lua模式也使用 % 转义魔术字符)。使用括号来获取节点及其内容:

data = string.match(Stream, "^.+(<TheNodeImLookingFor>.+</TheNodeImLookingFor>).+$")

或者只获取内容:

data = string.match(Stream, "^.+<TheNodeImLookingFor>(.+)</TheNodeImLookingFor>.+$")
2014-05-09 07:37:25