[Tips and Tricks] LINQ to XML with xmlns

If your XML file has xmlns, you may be run into problem when get some XML data with LINQ.

How to fix this?

1. prepend the namespace

XNamespace ns = doc.Root.Name.Namespace;
var cars2 = from d in doc.Descendants(ns + "CarForSale") select d;

2. search by local name:

var cars2 = from d in doc.Descendants() 
            where d.Name.LocalName == "CarForSale" 
            select d;

你可能感兴趣的:(LINQ)