0

Given the following XML -

<Response>
  <Item name="ItemA" />
</Response>

How do I get the value of the name attribute?

I have tried several ways with no luck, here was the last try- (Note that writing the contents of 'xml' to the console displayed the above XML)

Dim doc As XDocument = XDocument.Load(xml)
Dim result = From x In doc.Descendants("Item") Select x.Attribute("Name").Value
Console.WriteLine(result)

Results in output of: "System.Linq.Enumerable.WhereSelectEnumerableIterator[Of System.Xml.Linq.XElement, String]"

Thanks,

1
  • Linq is case sensitive. You have a capital 'N' instead of a small 'n'. Commented May 14, 2017 at 8:33

2 Answers 2

2

For that exact XML structure you can do as follows :

Dim result =  doc.Root.Element("Item").Attribute("name").Value

Notice that Element() returns single child element of a given name.

In case there is XML namespace involved, as you mentioned in the comment below, you need to use a combination of XNamespace and the element's local-name to reference Item element :

Dim path As XNamespace = "path"
Dim result = doc.Root.Element(path+"Item").Attribute("name").Value
Sign up to request clarification or add additional context in comments.

5 Comments

An unhandled exception of type 'System.NullReferenceException' occurred Object reference not set to an instance of an object.
@Dan ah the attribute is in all-lower-case 'name', not 'Name'
Sorry I didn't catch that. It is working. What change would need made if a namespace were added? <Response xmlns="path">
@Dan I added solution to that in the answer
Thanks for confirming that for me. All is working and your help is greatly appreciated!
1

I prefer XElement, a lot less typing.

    Dim xe As XElement
    ' to load from a file
    ' Dim yourpath As String = "your path here"
    ' Dim xe As XElement = XElement.Load(yourpath)

    ' for testing
    xe = <Response>
             <Item name="ItemA"/>
         </Response>

    Dim result As String = xe.<Item>.@name '<<<<<<<<<<<<<<<<<<< answer

1 Comment

@Dan - take a look at using XElement

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.