Bill Norman
Bill Norman

Reputation: 881

VB 2010 XML files with namespaces are causing trouble

I'm trying to parse out an XML file using LINQ (XDocument) and there's something about having a namespace in the document that screws everything up.

I found this SO question about the same thing affecting element names, and I got past that (using the Name.LocalName property). But it's causing the same problem with other functions, such as getting an element with a specific name. For example:

The XML code in brief:

<FeatureDefinitions xmlns="http://website.com/schema/features">
    <FeatureDefinition  Name="FeatureOne" >
      <Attributes>
        <ListAttribute Name="TYPE" Description="MATERIAL USED.">
          <ListItems>
            <Item>Material 1</Item>
            <Item>Material 2</Item>
            <Item>OTHER </Item>
          </ListItems>
        </ListAttribute>
        <ListAttribute Name="POSITION">
          <ListItems>
            <Item>BEGIN</Item>
            <Item>EDGE</Item>
            <Item>END</Item>
            <Item>TOE</Item>
            <Item>TOP</Item>
          </ListItems>
        </ListAttribute>
        <StringAttribute Name="NOTES" />
      </Attributes>
    </FeatureDefinition>
</FeatureDefinitions>

Then in the code:

Dim nodeFeatureDef as XElement = nodeFeatureDefinitions.Element("Attributes")

So, what's happening now is that when the name space is included in the first line of the XML, I can't get the element("Attributes") and its associated nodes. But if I delete the namespace attribute in the first line, it works fine.

There are lots of forums in which it is suggested that the VB source code import the namespace, but I can't be sure every file that this processes will have the same namespace. It worked by using the Name.LocalName property to the Name property, but I don't know how to do the same thing to the Elements property.

Any ideas?

Thanks!

Upvotes: 0

Views: 80

Answers (1)

Mark
Mark

Reputation: 8160

If the namespace is unknown, you could get it from the root element:

Dim xml As XDocument = ...
Dim ns = xml.Root.Name.Namespace

You can then use the XNamespace.GetName method to create a qualified name, e.g.

Dim attrs = xml.Descendants(ns.GetName("ListAttribute"))

This should also work OK if there is no namespace on the root element.

Upvotes: 2

Related Questions