dimanche 28 juin 2015

Powershell: [xml].SelectNodes doesn't return expected results?

I'm using powershell to parse a C# project file, which is a standard xml file:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://ift.tt/PiGwmX" ToolsVersion="4.0">
    <PropertyGroup>
        <ProjectType>Local</ProjectType>
    </PropertyGroup>
    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <CodeAnalysisRules>-Microsoft.Design#CA2210;Microsoft</CodeAnalysisRules>
        <PlatformTarget>AnyCPU</PlatformTarget>
    </PropertyGroup>
</Project>

I wish to select out "CodeAnalysisRules" tag content using "SelectNodes" function:

function f($fileName)
{
    Write-Host "Parsing $fileName"
    [xml]$xml=Get-Content $fileName
    if([String]::IsNullOrEmpty($xml.Project.NamespaceURI))
    {
        write-Host "skip!" -ForegroundColor Yellow
    }
    else
    {
        [System.Xml.XmlNamespaceManager]$ns = $xml.NameTable
        $ns.AddNamespace("Any", $xml.DocumentElement.NamespaceURI)
        $ns
        $nodes = $xml.SelectNodes("//CodeAnalysisRules",$ns)
        $nodes.Count
    }
}
f d:\m.xml

I expected to get the string inside but in fact I got:

Parsing d:\m.xml

xmlns
xml
Any
0

Anything wrong with my program or assumption? Thanks!

Aucun commentaire:

Enregistrer un commentaire