xn/Transformation/ContextFunctions.cs
Dominic Höglinger 154647083c fix: port transformation layer from XmlDocument to XDocument
- Thread runtime Context through expression trees via ParameterExpression
  instead of baking a parse-time constant (Node was always null)
- Fix ExpressionPart to compile Func<Context,string> and invoke with live ctx
- Coerce double arithmetic expressions to string before lambda wrapping
- Remove HasAttributes guard in attr() that blocked new attribute creation
- Replace GetLevel(XmlNode) with XElement.Parent-based implementation
- Add cdata()/cdata(txt) functions to read/write CDATA nodes in place,
  preserving the XCData wrapper that SetValue() would destroy

Clanker: claude-sonnet_4.6
2026-04-24 04:44:59 +02:00

73 lines
1.7 KiB
C#

using System;
using Sprache;
using XNeedle.Parser;
using XNeedle.Parser.Elements;
namespace XNeedle.Transformation
{
public class ContextFunctions
{
public static string hex(Context ctx, double value)
{
uint v = (uint)value;
return $"#x{v:X8}";
}
public static double GetLevel(Context ctx)
{
int level = 0;
System.Xml.Linq.XElement? n = ctx.Node;
while (null != (n = n?.Parent))
level++;
return level;
}
public static double crc(Context ctx)
{
if (ctx.Node is null)
{
return 0;
}
int crc = 0xAFFE;
return (double)crc;
}
public static string text(Context ctx)
{
if (ctx.Node is null) return "";
return ctx.Node.Value;
}
public static string text(Context ctx, string txt)
{
if (ctx.Node is null) return "";
ctx.Node.SetValue(txt);
return txt;
}
public static string attr(Context ctx, string name, string value)
{
if (ctx.Node is null) return "";
var attr = ctx.Node.Attribute(name);
if (attr != null)
{
attr.Value = value;
}
else
{
ctx.Node.SetAttributeValue(name, value);
}
return "";
}
public static string attr(Context ctx, string name)
{
var attr = ctx.Node?.Attribute(name);
if (attr != null)
{
return attr.Value;
}
return "";
}
}
}