4

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 take out the xmlns="HTTP..." my code outputs "NuSpecID", but I cannot find a solution that allows me to parse/query this XML with the namespace still attached.

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

1 Answer 1

5

You need to import the namespace to use in XML literals.

At the top of the module, put:

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

Obviously you can use anything instead of ns.

Sign up to request clarification or add additional context in comments.

3 Comments

Or you could set the default namespace with Imports <xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"> so you don't have to specify the namespace every time.
I have adjusted my question, i have multiple options for namespaces based on what file i select. how do i write one function that can have different namespaces?
@theB3RV You are supposed to know what namespaces your XMLs use, that is the whole point of namespaces. If you do know what namespace each file contains, Import them all at the top of your module with different prefixes and use accordingly. If you don't know the namespaces, which means you don't care about them and what to ignore them, then write your XML queries in the form of From el In Root.Elements Where el.Name.LocalName = "metadata" Select el.

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.