Parsing Visual Studio Project File as XML

2019-07-20 05:29发布

问题:

Using a dynamic xml parser, I'm trying to load a VS Project file as an XElement. Here is a slimmed down version of the project file:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ItemGroup>
    </ItemGroup>
    <ItemGroup>
    </ItemGroup>
</Project>

The file appears to load in the sense that when I ToString(), I get the contents. However, when trying to pick out elements, nothing is ever found:

XElement element;

public DynamicXmlParser( string fileName )
{
    element = XElement.Load( fileName );
}

public override bool TryGetMember( GetMemberBinder binder, out object result )
{
    result = null;
    if ( element == null ) return false;

    XElement subElement = element.Element( binder.Name );

    if ( subElement == null ) return false;

    result = new DynamicXmlParser( subElement );
    return true;
}

subElement is always null.

binder.Name is ItemGroup

dynamic xmlDoc = new DynamicXmlParser( SampleFileName );
Debug.Pring(xmlDoc.ItemGroup.ToString());

However, when I remove all attributes from the Project node, subElement becomes an ItemGroup XElement as expected.

Why can I return any elements when the attributes are in the project node?

回答1:

You are probably asking for elements in empty namespace why in fact the elements live in xmlns="http://schemas.microsoft.com/developer/msbuild/2003". Take a look at XNamespace.

For instance try:

XNamespace msbuildNs = "http://schemas.microsoft.com/developer/msbuild/2003"
XElement subElement = element.Element(msbuildNs + binder.Name);