I've found some code to serialize classes to XmlElement here: How do I convert a C# class to an XMLElement or XMLDocument More specifically, I used Dave Andersen's solution.
public static XmlElement SerializeToXmlElement(object o)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter writer = doc.CreateNavigator().AppendChild())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
}
return doc.DocumentElement;
}
I realized however, that when I use the GetElementById
-function on the created document, the result is always null.
After some snooping around, I found that XmlDocument uses an internal list named _htElementIdMap
.
This list seems to not be initialized.
So far I haven't been able to figuere out what I'm doing wrong, or wether I'm maybe trying to do something that is not supported. Does anybody know how I can fix this?
Thank you in advance
Edit:
The simplified version of what I do is the following
public static void Main(String[] args)
{
var timestamp = new TimestampType
{
Id = "Test1",
Created = new AttributedDateTime
{
Value = DateTime.Now.ToUniversalTime().ToString("o")
},
Expires = new AttributedDateTime
{
Value = DateTime.Now.AddDays(1).ToUniversalTime().ToString("o")
}
};
var timestampXmlElement = SerializeToXmlElement(timestamp);
var result1 = timestampXmlElement.OwnerDocument.GetElementById("Test1");
}
public static XmlElement SerializeToXmlElement(object o)
{
XmlDocument doc = new XmlDocument();
using (XmlWriter writer = doc.CreateNavigator().AppendChild())
{
new XmlSerializer(o.GetType()).Serialize(writer, o);
}
return doc.DocumentElement;
}
the problem is that result1 is null.
this is the xml for timestampXmlElement :
<Timestamp xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" p3:Id="Test1" xmlns:p3="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<p3:Created>2018-06-12T12:58:20.5213777Z</p3:Created>
<p3:Expires>2018-06-13T12:58:20.5249304Z</p3:Expires>
</Timestamp>