如何通过Lua解析具有多个出现次数的xml文件特定标签的属性值?

这是我的主 XML 文件 oem.xml 的一个简短片段 -

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Service>
<NewInstance ref="a39d725e7689b99e91af6fcb68bc5ec2">
<Std>DiscoveredElement</Std>
<Key>a39d725e7689b99e91af6fcb68bc5ec2</Key>
<Attributes>
<Attribute name="group" value="OEM All Targets On uxunt200.schneider.com" />
</Attributes>
</NewInstance>
<NewRelationship>
<Parent>
<Instance ref="a39d725e7689b99e91af6fcb68bc5ec2" />
</Parent>
<Components>
<Instance ref="E0246C56D81A7A79559669CD16A8B555" />
<Instance ref="2D5481A0EA3F81AC1E06E2C32231F41B" />
</Components>
<NewInstance ref="E961625723F5FDC8BD550077282E074C">
<Std>DiscoveredElement</Std>
<Key>E961625723F5FDC8BD550077282E074C</Key>
<Attributes>
<Attribute name="ServerNames" value="WLS_B2B4a" />
<Attribute name="orcl_gtp_os" value="Linux" />
<Attribute name="ORACLE_HOME" value="" />
</NewInstance>
</Service>

现在,我想打印出所有 <Attribute> 标签出现的属性值和名称文本 (例如 Attribute name="ServerNames" value="WLS_B2B4a")。

我尝试了以下代码 :

require("LuaXml")
local file = xml.load("oem.xml")
local search = file:find("Attributes")

for Attribute = 1, #search do
  print(search[Attribute].value)
  print(search[Attribute].name)
end

这只为属性标签的第一个出现给出了结果。我想解析到文件末尾,以查找所有出现的属性。 请使用 LuaXml 库提供一个解决方案。

点赞
用户2546626
用户2546626

LuaXML 看起来非常简洁,xml.find 声明:

返回第一个满足搜索条件的(子)表或 nil。

一个更简单的解决方案是使用 Lua 字符串模式:

local file = io.open("oem.xml", "rb")   -- 打开文件以读取(二进制数据)
for name, value in file:read("*a"):gmatch("<Attribute name=\"(.-)\" value=\"(.-)\" />") do  -- 读取整个文件内容并迭代属性匹配
    print(string.format("Name: %s\nValue: %s", name, value))    -- 打印我们得到的内容
end
file:close()    -- 关闭文件(以即时锁定,无需等待垃圾回收器)

不要忘记检查 file 是否有效。

2015-09-15 10:26:56