ElektroStudios ElektroStudios - 1 year ago 58
Vb.net Question

Simplify syntax when working with XML namespaces

In a simple .vbproj file like this:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />

I would like to store a collection of
elements. The problem I found is the need to specify the (long) namespace everytime that I call

string text = File.ReadAllText("My project.vbproj");
XDocument doc = XDocument.Parse(text, LoadOptions.None);

IEnumerable<XElement> propGroups =

I'm pretty sure should exists a better friendly syntax to simplify the code above, maybe to call just once
instead of
, or maybe to avoid specifying the namespace (or mroe than once) with a proper XPath and using
instead, however, seems that I cannot use XPATH v2.0 to ignore the namespace like
(or maybe my syntax is wrong?).

Someone could explain me how can I refactor it?.

Note that the purpose is to modify some properties of the Xml then save the changes in the file, not just to get the data that is inside the Xml (if that matters for a solution).

Answer Source

If you're not particularly interested in explicitly identifying that Project is the direct parent of PropertyGroup, you can instead use Descendants to find all PropertyGroup elements no matter where they appear in the document:

XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
var propGroups = doc.Descendants(ns + "PropertyGroup");

The intention of the API was to the use the + operator to combine a namespace with a local name to avoid the verbosity of including it for each name. There's no simple way of avoiding using the namespace if you want to identify the element using it. Filtering by local name is far more verbose than this.