Skip to content

Commit

Permalink
[chore][pkg/ottl] Apply more standards to RemoveXML converter (#35463)
Browse files Browse the repository at this point in the history
This PR just applies a couple more standards that I've been following
with the other XML converters. Namely:
- Create the function via the factory to ensure the constructor
validation is applied
- Use `xmlquery.QueryAll` instead of the deprecated `xmlquery.FindEach`
  • Loading branch information
djaglowski authored Sep 27, 2024
1 parent 4b90b60 commit 3033832
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
12 changes: 9 additions & 3 deletions pkg/ottl/ottlfuncs/func_remove_xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@ func removeXML[K any](target ottl.StringGetter[K], xPath string) ottl.ExprFunc[K
} else if doc, err = parseNodesXML(targetVal); err != nil {
return nil, err
}
xmlquery.FindEach(doc, xPath, func(_ int, n *xmlquery.Node) {

nodes, err := xmlquery.QueryAll(doc, xPath)
if err != nil {
return nil, err
}

for _, n := range nodes {
switch n.Type {
case xmlquery.ElementNode:
xmlquery.RemoveFromTree(n)
Expand All @@ -60,7 +66,7 @@ func removeXML[K any](target ottl.StringGetter[K], xPath string) ottl.ExprFunc[K
case xmlquery.CharDataNode:
xmlquery.RemoveFromTree(n)
}
})
}
return doc.OutputXML(false), nil
}
}
Expand All @@ -82,7 +88,7 @@ func parseNodesXML(targetVal string) (*xmlquery.Node, error) {
if err != nil {
return nil, fmt.Errorf("parse xml: %w", err)
}
if !preserveDeclearation {
if !preserveDeclearation && top.FirstChild != nil {
xmlquery.RemoveFromTree(top.FirstChild)
}
return top, nil
Expand Down
25 changes: 19 additions & 6 deletions pkg/ottl/ottlfuncs/func_remove_xml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,28 @@ func Test_RemoveXML(t *testing.T) {
xPath: "//text()['*delete*']",
want: `<?xml version="1.0" encoding="UTF-8"?><a></a>`,
},
{
name: "ignore empty",
document: ``,
xPath: "/",
want: ``,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
target := ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return tt.document, nil
},
}
exprFunc := removeXML(target, tt.xPath)
factory := NewRemoveXMLFactory[any]()
exprFunc, err := factory.CreateFunction(
ottl.FunctionContext{},
&RemoveXMLArguments[any]{
Target: ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return tt.document, nil
},
},
XPath: tt.xPath,
})
assert.NoError(t, err)

result, err := exprFunc(context.Background(), nil)
assert.NoError(t, err)
assert.Equal(t, tt.want, result)
Expand Down

0 comments on commit 3033832

Please sign in to comment.