Using LINQ in VB.NET with Namespaces

I have this xml file:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>NuSpecID</id>
    <version>1.0.0</version>
    <title>NuSpec Sample</title>
    <authors>Jim Bob</authors>
    <owners>Billy Joel</owners>
    <licenseUrl>http://url.goes.here</licenseUrl>
    <projectUrl>http://url.goes.there</projectUrl>
    <requireLicenseAcceptance>ture</requireLicenseAcceptance>
    <description>this is a sample nuget.</description>
    <summary>
  </metadata>
</package>

and this code:

Module Module1
    Sub Main()
        Dim root As XElement = XElement.Load("c:\tmp\nuspec.xml")
        Dim tests As IEnumerable(Of XElement) = _
            From el In root.<metadata> _
            Select el
        For Each el As XElement In tests
            Console.WriteLine(el.<id>.Value)
        Next
        Console.ReadKey()
    End Sub
End Module

If I xmlns="HTTP..."output my "NuSpecID" code outputs, but I cannot find a solution that allows me to parse / query this XML with a namespace still attached.

I also have some files that do not have a namespace or have another, how to determine whether to use it and which one to use?

+4
source share
1 answer

You need to import a namespace for use in XML literals.

At the top of the module, place:

Imports <xmlns:ns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">

Then in your function:

Dim tests = root.<ns:metadata>

For Each el In tests
    Console.WriteLine(el.<ns:id>.Value)
Next

, - ns.

+5

Source: https://habr.com/ru/post/1529827/


All Articles