Try to include xml node children in lua table

This commit is contained in:
2025-03-26 02:50:28 +01:00
parent 1a4b4f76f2
commit 66a522aa12
2 changed files with 47 additions and 36 deletions

View File

@@ -43,10 +43,11 @@ func (p *XMLProcessor) ProcessContent(content string, path string, luaExpr strin
}
defer L.Close()
err = p.ToLua(L, node)
table, err := p.ToLua(L, node)
if err != nil {
return content, modCount, matchCount, fmt.Errorf("error converting to Lua: %v", err)
}
L.SetGlobal("v", table)
err = L.DoString(BuildLuaScript(luaExpr))
if err != nil {
@@ -92,11 +93,11 @@ func (p *XMLProcessor) ProcessContent(content string, path string, luaExpr strin
}
// ToLua converts XML node values to Lua variables
func (p *XMLProcessor) ToLua(L *lua.LState, data interface{}) error {
func (p *XMLProcessor) ToLua(L *lua.LState, data interface{}) (lua.LValue, error) {
// Check if data is an xmlquery.Node
node, ok := data.(*xmlquery.Node)
if !ok {
return fmt.Errorf("expected xmlquery.Node, got %T", data)
return nil, fmt.Errorf("expected xmlquery.Node, got %T", data)
}
// Create a simple table with essential data
@@ -107,17 +108,25 @@ func (p *XMLProcessor) ToLua(L *lua.LState, data interface{}) error {
L.SetField(table, "name", lua.LString(node.Data))
L.SetField(table, "value", lua.LString(node.InnerText()))
// Add attributes if any
// Add children if any
children := L.NewTable()
for child := node.FirstChild; child != nil; child = child.NextSibling {
childTable, err := p.ToLua(L, child)
if err == nil {
children.Append(childTable)
}
}
L.SetField(table, "children", children)
attrs := L.NewTable()
if len(node.Attr) > 0 {
attrs := L.NewTable()
for _, attr := range node.Attr {
L.SetField(attrs, attr.Name.Local, lua.LString(attr.Value))
}
L.SetField(table, "attr", attrs)
}
L.SetField(table, "attr", attrs)
L.SetGlobal("v", table)
return nil
return table, nil
}
// FromLua gets modified values from Lua