.netxmlxml-signature

.NET Signed XML Prefix


Is there a way to set the prefix on the Signature of a Signed XML Document (SignedXml class in .Net)?

So instead of:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#>
...
</Signature>

I could have the following:

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#>
...
</ds:Signature>

Solution

  • First of all, there really isn't any good reason to do this. The two forms are functionally equivalent. Any well-behaved XML processor will handle them absolutely identically. So unless you are trying to talk to an application that doesn't properly implement XML namespaces, it's better (IMO) just to leave the default form alone. (And even in that case, it would be better, if at all possible, to get the faulty application fixed instead.)

    That said, you can manually set the prefix on the XmlElement that is returned by SignedXml.GetXml() and its child elements using XPath like this:

    XmlElement signature = signedXml.GetXml();
    foreach (XmlNode node in signature.SelectNodes(
        "descendant-or-self::*[namespace-uri()='http://www.w3.org/2000/09/xmldsig#']"))
    {
        node.Prefix = "ds";
    }