WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

What is wrong with this XML that is preventing linq from working?

    Dim root As XElement = XElement.Load(xmlFile)
    Dim stuff =
        From item In root.Elements("abc") Select item

    Debug.Print(stuff.Count)

and the contents of the XML are:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook
 xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
  <abc xmlns="foo">1</abc>
  <abc xmlns="foo">2</abc>
  <abc xmlns="foo">3</abc>
</Workbook>

If I remove xmlns="urn:schemas-microsoft-com:office:spreadsheet" the beginning of the the Workbook tag, I get the correct result of 3

ETA What do I do if I have another namespace embedded, in this case "foo"

Upvotes: 0

Views: 141

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500903

You're trying to find an element with a name abc without any namespace. The xmlns=... part of the parent element sets the default namespace for descendant elements.

You need:

Dim ns As XNamespace = "urn:schemas-microsoft-com:office:spreadsheet"
...
Dim stuff = root.Elements(ns + "abc")

Note that there's no point in using a query expression here - if you're just doing From x in y Select x you can just use y instead...

Upvotes: 2

Related Questions