1

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://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?

1 Answer 1

2

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.