Could you help me in improving performance? It is in C#.
Without code? No. Show some code, and we might stand a chance.
However, XmlSerializer
is going to be much better at this than you. Serialization looks simple from the outside, but there are lots of edge cases and pitfalls, and avoiding those while maintaining performance is hard.
But: a model of 200/300 elements should be basically instant; if it is taking 46 seconds, either there is something horribly wrong in your code that I can't speculate about (please show code if you want input here!), or: you're processing a few GiB of data.
Here's a runnable example that caters to your basic model while also supporting the unknown attributes/elements alluded to in the comments:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
var xml = """
<root>
<test>
<testchild>
</testchild>
<testchild>
</testchild>
</test>
<test>
<testchild id="42" name="fred">
</testchild>
<testchild>
</testchild>
</test>
</root>
""";
var serializer = new XmlSerializer(typeof(MyRoot));
var obj = (MyRoot)serializer.Deserialize(XmlReader.Create(new StringReader(xml)))!;
Console.WriteLine(obj.Tests.Sum(x => x.Children.Count));
Console.WriteLine(obj.Tests[1].Children[0].GetAttribute("id"));
[XmlRoot("root")]
public class MyRoot
{
[XmlElement("test")]
public List<MyTest> Tests { get; } = new();
}
public class MyTest
{
[XmlElement("testchild")]
public List<MyChild> Children { get; } = new();
}
public class MyChild {
public string? GetAttribute(string name)
=> attributes?.SingleOrDefault(x => x.Name == name)?.Value;
public string? GetElement(string name)
=> elements?.SingleOrDefault(x => x.Name == name)?.Value;
private List<XmlElement>? elements;
private List<XmlAttribute>? attributes;
[XmlAnyAttribute]
public List<XmlAttribute> Attributes => attributes ??= new();
[XmlAnyElement]
public List<XmlElement> Elements => elements ??= new();
}