Search code examples
c#xmlxmldocument

Can't Parse XML from XRDS document


How do I parse the XML below? I think the probably is the my code couldn't understand the starting point. I have tried both techniques below and it doesn't work.

Response.Write(xmlDoc.SelectSingleNode("/xrds/XRD").InnerXml);  //Parse it - failed
Response.Write(xmlDoc.SelectSingleNode("/XRD").InnerXml);       //failed

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
string gtest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xrds:XRDS xmlns:xrds=\"xri://$xrds\" xmlns=\"xri://$xrd*($v*2.0)\"><XRD><Service priority=\"0\"><Type>http://specs.openid.net/auth/2.0/server</Type><Type>http://openid.net/sreg/1.0</Type> <URI>https://www.mydomain.com/login</URI></Service></XRD></xrds:XRDS>";
xmlDoc.LoadXml(gtest);//Load data into the xml.
Response.Write(xmlDoc.SelectSingleNode("/xrds/XRD").InnerXml);//Parse XML

Solution

  • You can use any of the below --

    xmlDoc.GetElementsByTagName("XRD")[0].InnerXml
    
    xmlDoc.DocumentElement.ChildNodes[0].InnerXml
    

    But if you have multiple XRD node then you can iterate through all of them and can parse them.

            XmlDocument xmlDoc = new XmlDocument();
            string gtest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xrds:XRDS xmlns:xrds=\"xri://$xrds\" xmlns=\"xri://$xrd*($v*2.0)\"><XRD><Service priority=\"0\"><Type>http://specs.openid.net/auth/2.0/server</Type><Type>http://openid.net/sreg/1.0</Type> <URI>https://www.mydomain.com/login</URI></Service></XRD></xrds:XRDS>";
            xmlDoc.LoadXml(gtest);//Load data into the xml.
            XmlNodeList nodeList = xmlDoc.GetElementsByTagName("XRD");
            foreach (XmlNode node in nodeList)
            {
                Console.Write(node.InnerXml);
            }