Use Linq to Xml with Xml namespaces

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

I have this code :

/*string theXml =
@\"

        
4条回答
  •  被撕碎了的回忆
    2020-11-22 16:01

    You can pass an XName with a namespace to Descendants() and Element(). When you pass a string to Descendants(), it is implicitly converted to an XName with no namespace.

    To create a XName in a namespace, you create a XNamespace and concatenate it to the element local-name (a string).

    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"),
                                  };
    

    There is also a shorthand form for creating a XName with a namespace via implicit conversion from string.

    var elements = from data in xmlElements.Descendants("{http://myvalue.com}Result")
                       select new
                                  {
                                      TheBool = (bool)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheBool"),
                                      TheId = (int)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheId"),
                                  };
    

    Alternatively, you could query against XElement.Name.LocalName.

    var elements = from data in xmlElements.Descendants()
                       where data.Name.LocalName == "Result"
    

提交回复
热议问题