Use Linq to Xml with Xml namespaces

前端 未结 4 1821
深忆病人
深忆病人 2020-11-22 15:19

I have this code :

/*string theXml =
@\"

        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 16:09

    LINQ to XML methods like Descendants and Element take an XName as an argument. There is a conversion from string to XName that is happening automatically for you. You can fix this by adding an XNamespace before the strings in your Descendants and Element calls. Watch out because you have 2 different namespaces at work.

    
    string theXml =
                    @"true1";
    
                //string theXml = @"true1";
    
        XDocument xmlElements = XDocument.Parse( theXml );
        XNamespace ns = "http://myvalue.com";
        XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
        var elements = from data in xmlElements.Descendants( ns + "Result" )
              select new
                     {
                         TheBool = (bool) data.Element( nsa + "TheBool" ),
                         TheId = (int) data.Element( nsa + "TheId" ),
                     };
    
        foreach ( var element in elements )
        {
            Console.WriteLine( element.TheBool );
            Console.WriteLine( element.TheId );
        }
    
    

    Notice the use of ns in Descendants and nsa in Elements

提交回复
热议问题