Change the default XML xmlns namespace value in .NET
I need to get a list of files from a VS project file. csproj file is XML file, so I use linq to xml to parse it. The problem is in default namespace of csproj file, it is declared like:
xmlns="http:/开发者_JS百科/schemas.microsoft.com/developer/msbuild/2003"
Here is the code I use to find "Compile" elements in a csproj file:
XmlReader reader = XmlReader.Create(projectFilePath);
XDocument doc = XDocument.Load(reader);
XmlNameTable nameTable = reader.NameTable;
XmlNamespaceManager nsManager = new XmlNamespaceManager(nameTable);
XNamespace nms = doc.Root.GetDefaultNamespace();
nsManager.AddNamespace("", nms.NamespaceName);
List<XElement> csFiles = new List<XElement>(doc.Root.XPathSelectElements("//Compile", nsManager));
doc.Root.XPathSelectElements
returns an empty list.
nsManager.DefaultNamespace
has value "http://schemas.microsoft.com/developer/msbuild/2003".
But nsManager.LookupNamespace("xmlns")
returns default XML namespace: "http://www.w3.org/2000/xmlns/".
How to change the xmlns namespace value?
Your problem is that you need to be explicit about the namespace with the XPath. It won't just use the default one for the document, you have to name it.
If you change the last two lines to something like this, it will work (I chose the xmlns prefix "default"):
nsManager.AddNamespace("default", nms.NamespaceName);
List<XElement> csFiles = new List<XElement>(doc.Root.XPathSelectElements("//default:Compile", nsManager));
Another option is to use the XContainer methods instead. This way you don't need to worry about using a namespace manager:
XNamespace nms = doc.Root.GetDefaultNamespace();
List<XElement> csFiles = new List<XElement>(doc.Root.Descendants(nms + "Compile"));
精彩评论