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

标签 xml parsing lua luaxml

这是我名为 oem.xml 的主要 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>

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

我尝试了以下代码:

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 库的解决方案。

最佳答案

LuaXML 看起来非常简单,xml.find 指出:

Returns the first (sub-)table which matches the search condition or nil.

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

local file = io.open("oem.xml", "rb")   -- Open file for reading (binary data)
for name, value in file:read("*a"):gmatch("<Attribute name=\"(.-)\" value=\"(.-)\" />") do  -- Read whole file content and iterate through attribute matches
    print(string.format("Name: %s\nValue: %s", name, value))    -- Print what we got
end
file:close()    -- Close file (for instant lock-free, no waiting for garbage collector)

不要忘记检查文件是否有效。

关于xml - 如何通过Lua解析多次出现的xml文件的特定标签的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32579136/

相关文章:

sockets - lua socket 多次接收报告相同的数据

java - Photoshop 图片在 Android 应用程序开发中无法运行(使用 Eclipse)

java - 如何在多个标签的情况下使用 Spring Batch 有效解析 XML

java - 从 Java 发送 XPath 变量

java - 在 Java 中合并两个 XML 文件

python - 如何使用python解析日志文件并将数据存储在数据库中?

html - 在 XPath 中将货币与美元符号 ($) 和逗号 (,) 匹配

javascript - 外部解析 RSS 提要,无需任何库(如 google 和服务器端)

lua - 传递给 Pandoc 的变量可以在 lua-filter 中使用吗?

lua - 具有大循环的 Redis Lua 脚本