getelementById在将对象序列化到c#.net中的XmlDocument后返回null

getelementById在将对象序列化到c#.net中的XmlDocument后返回null,c#,xml,serialization,C#,Xml,Serialization,我在这里找到了一些将类序列化为XmlElement的代码: 更具体地说,我使用了这个解决方案 public static XmlElement SerializeToXmlElement(object o) { XmlDocument doc = new XmlDocument(); using(XmlWriter writer = doc.CreateNavigator().AppendChild()) { new XmlSerializer(o.Get

我在这里找到了一些将类序列化为XmlElement的代码: 更具体地说,我使用了这个解决方案

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;
}
然而,我意识到,当我对创建的文档使用
GetElementById
-函数时,结果总是空的。 经过仔细观察,我发现XmlDocument使用了一个名为
\u htElementIdMap
的内部列表。 此列表似乎未初始化

到目前为止,我还无法找出我做错了什么,或者我是否试图做一些不受支持的事情。 有人知道我怎么解决这个问题吗

先谢谢你

编辑:

我所做的简化版本如下

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;
}
问题是result1为空

这是timestampXmlElement的xml:

<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>

2018-06-12T12:58:20.5213777Z
2018-06-13T12:58:20.5249304Z

?您可能对名称空间有问题。您需要查看xml的字符串版本才能找到解决方案。使用ToString()方法并发布xml示例以获得解决方案。@AlexanderPetrov我正在编写的代码应该用于创建签名soap信封。它在ComputeSignature()函数的System.Security.Cryptography.Xml.SignedXml类中崩溃。我发现这就是调用GetElementById的地方。这就是为什么我在这里问是否有人知道为什么这不起作用。@jdweng您是指xml名称空间吗?我正在转换的C#类都是由xsd工具根据我在网上找到的模式生成的。我遇到过这个问题,即使在转换一些类的最小值时也是如此。是的。您正在将这些类转换为XmlDocument(或XmlElement),其中将包含xsd工具创建的名称空间。然后使用需要名称空间的GetElementById解析结果。您在GetElementById中使用的名称空间是什么?你有例外吗?要么生成的xml不正确,要么得到异常,要么GetElementById需要名称空间。