3

これは、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 ) のテキストを出力したいと考えています。<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 ライブラリを使用した解決策を提案してください。

4

1 に答える 1

2

LuaXMLはかなり最小限のようで、次のようにxml.find述べています。

検索条件または 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)

file有効であることを確認することを忘れないでください。

于 2015-09-15T10:26:56.470 に答える