This is a simple stuff but driving me really crazy now. Spent hours on figuring this out which I have many many times before.
I am trying to read a parse xmlsimple doc. But I don't know why can't access elements by index number. I can't understand the problem, when I try this in the console it works, but not in actual code. It gives me this error on the view page:
undefined method `[]' for nil:NilClass
Code:
@i = 0
list =""
while @i <= 2
puts xml
a = parsed_items["Item"][@i]["ItemId"]
list << a.to_s << ","
@i += 1
end
puts list.to_s
If I do it by giving a int value manually in my code then it works:
a = parsed_items["Item"][0]["ItemId"] # it works with other exact code
Change to @i
and not working:
a = parsed_items["Item"][@i]["ItemId"] # it does not work with other exact code
XML:
1.9.2p290 :013 > items = "<ItemList> <Item> <ItemId>123</ItemId> <ItemName>abc</ItemName> <ItemType>xyz</ItemType> <Status>bad</Status> </Item> <Item> <ItemId>456</ItemId> <ItemName>fgh</ItemName> <ItemType>nbv</ItemType> <Status>bad</Status> </Item> </ItemList>"
=> "<ItemList> <Item> <ItemId>123</ItemId> <ItemName>abc</ItemName> <ItemType>xyz</ItemType> <Status>bad</Status> </Item> <Item> <ItemId>456</ItemId> <ItemName>fgh</ItemName> <ItemType>nbv</ItemType> <Status>bad</Status> </Item> </ItemList>"
1.9.2p290 :014 > parsed_items = XmlSimple.xml_in(items, { 'KeyAttr' => 'name' })
=> {"Item"=>[{"ItemId"=>["123"], "ItemName"=>["abc"], "ItemType"=>["xyz"], "Status"=>["bad"]}, {"ItemId"=>["456"], "ItemName"=>["fgh"], "ItemType"=>["nbv"], "Status"=>["bad"]}]}
XML:
<ItemList>
<Item>
<ItemId>123</ItemId>
<ItemName>abc</ItemName>
<ItemType>xyz</ItemType>
<Status>bad</Status>
</Item>
<Item>
<ItemId>456</ItemId>
<ItemName>fgh</ItemName>
<ItemType>nbv</ItemType>
<Status>bad</Status>
</Item>
</ItemList>