Parsing xml with name space with namespace prefix that appears twice

wantto wantto 1 Reputation point
2021-03-04T19:43:28.293+00:00

i have te next xml :

<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" 
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Consent="urn:oasis:names:tc:SAML:2.0:consent:obtained" 
>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </samlp:Status>
</samlp:Response>

i tried to parse it with next code (i want to get the value of the "value" attribute which is in : samlp:StatusCode):
XmlDocument xmlDocument=new ConfigXmlDocument();
what do i miss here?
xmlDocument.Load(@"c:\file1.xml");
//determine whether document contains namespace
var namespaceName = "samlp";
var namespacePrefix = string.Empty;
var xmlns = xmlDocument.FirstChild.Attributes?["xmlns:samlp"];
if (xmlns != null)
{
var nameSpaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
nameSpaceManager.AddNamespace(namespaceName, xmlns.Value);
namespacePrefix = namespaceName + ":";
}

            XmlNode node = xmlDocument.SelectSingleNode("StatusCode");
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,275 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Yitzhak Khabinsky 25,026 Reputation points
    2021-03-04T20:58:06.887+00:00

    Hi @wantto wantto ,

    It is better to use LINQ to XML API. It is available in the .Net Framework since 2007.

    XML

    <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"  
                    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"  
                    Consent="urn:oasis:names:tc:SAML:2.0:consent:obtained">  
     <samlp:Status>  
     <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>  
     </samlp:Status>  
    </samlp:Response>  
    

    c#

    void Main()  
    {  
     const string fileName = @"e:\Temp\wantto.xml";  
     XDocument xdoc = XDocument.Load(fileName);  
      
     XNamespace ns = xdoc.Root.GetNamespaceOfPrefix("samlp");  
     XElement xelem = xdoc.Descendants(ns + "StatusCode").FirstOrDefault();  
      
     Console.WriteLine("StatusCode: {0}", xelem.Attribute("Value").Value.Split(':').Select(sValue => sValue).ToArray().Last());  
    }  
    

    Output

    StatusCode: Success  
    
    1 person found this answer helpful.

  2. Viorel 112.5K Reputation points
    2021-03-04T20:05:10.417+00:00

    To get the value of attribute:

    XmlNamespaceManager nsm = new XmlNamespaceManager( xmlDocument.NameTable );
    nsm.AddNamespace( "samlp", "urn:oasis:names:tc:SAML:2.0:protocol" );
    
    string value = xmlDocument.SelectSingleNode( "/samlp:Response/samlp:Status/samlp:StatusCode/@Value", nsm ).Value;