0

My XML

<?xml version="1.0" encoding="utf-8"?>
<metadata created="2014-05-15T12:26:07.701Z" xmlns="http://site/cu-2.0#" xmlns:ext="http://site/cu/b-2.0">
  <customer-list count="47" offset="0">
    <customer id="7123456" type="Cust" ext:mark="1">
      <name>Tony Watt</name>
      <sort-name>Watt, Tony</sort-name>
      <gender>male</gender>
      <country>US</country>
      <knownAs-list>
        <knownAs locale="ko" sort-name="Tony Watt"</knownAs>
        <knownAs locale="ja" sort-name="Watt Tony"</knownAs>
      </knownAs-list>
      <tag-list>
          <begin>Country</begin>
          <tag count="1">
          <name>usa</name>
      </tag-list>
 </customer>
  <customer id="9876543" type="Cust" ext:mark="2">
....
</customer-list>

So i have some code that gets all the data. I went one step further to use Anonymous types and add the values into a class as below

Dim c = From cust As XElement In XDoc.Descendants(ns + "customer")
              Select New Customer() With {.Name = cust.Element(ns + "name"),
                                        .Surname = CStr(cust.Element(ns + "surname")),
                                        .Id = cust.Attribute("id"),
                                        .Tag = CStr(cust.Element("tag-list").Element("begin"))}

The above code returns data from the XML, but adding this line of code

.Tag = CStr(cust.Element("tag-list").Element("begin"))

throws an exception, "Object reference not set to an instance of an object". Now theres two possibilities here

  1. I have my code wrong for that particular line (to retrieve 'begin' from the 'tag-list' element)
  2. I know some tag-list elements dont have a nested begin element so that could be adding some confusion. I added Cstr to overcome this but not sure if this is enough?

After reading MSDN it seems using .Descendants (Xdoc.Descendants) would get the all the data from all elements where Elements would return data upto the path i have stated, so as far as i can tell the data 'should' be available with the above code. Could anyone assist me in getting the begin data from tag-list?

Computer
  • 2,149
  • 7
  • 34
  • 71

1 Answers1

1

The XML namespace declaration is missing. Use

.Tag = CStr(cust.Element(ns + "tag-list").Element(ns + "begin"))
dotnetom
  • 24,551
  • 9
  • 51
  • 54