Reputation: 52533
I have the following in an XML file:
<entry>
...
<link href="http://www.example.com/somelink" />
...
</entry>
I want to extract the "href" attribute. I've been getting my list of elements like so:
Dim productsDoc = XDocument.Parse(productXML.ToString())
Dim feed = From entry In productsDoc...<entry> Select entry
For Each entry In feed
Dim product As New CartItem
...
product._productid = entry.<id>.Value
product._permalink = entry.<link>.Value 'HOW DO I GET THE ATTRIBUTE?
allItems.Add(product)
Next
How do I extract the <link>
href attribute?
Thanks!
Upvotes: 1
Views: 878
Reputation: 21664
Hi to get the link you should use the "XML Attribute Axis Property". This allows you to easily access attributes.
You can use it like this:
'this is how you get the href string
product._permalink = entry.<link>.@href
Here's a full working example of usage:
Module Module1
' some products xml to use for this example
Dim productsXml As XElement = <Xml>
<Product>
<Name>Mountain Bike</Name>
<Price>59.99</Price>
<Link href="http://example.com/bike">Click here for a Mountain Bike</Link>
</Product>
<Product>
<Name>Arsenal Football</Name>
<Price>9.99</Price>
<Link href="http://example.com/arsenalfootball">Click here for a Arsenal Football</Link>
</Product>
<Product>
<Name>Formula One Cap</Name>
<Price>14.99</Price>
<Link href="http://example.com/f1cap">Click here for a Formula One Cap</Link>
</Product>
<Product>
<Name>Robin Hood Bow</Name>
<Price>8.99</Price>
<Link href="http://example.com/robinhoodbow">Click here for a Robin Hood Bow</Link>
</Product>
</Xml>
Sub Main()
' get all <Product> elements from the XDocument
Dim products = From product In productsXml...<Product> _
Select product
' go through each product
For Each product In products
' output the value of the <Name> element within product
Console.WriteLine("Product name is {0}", product.<Name>.Value)
' output the value of the <Price> element within product
Console.WriteLine("Product price is {0}", product.<Price>.Value)
' output the value of the <Link> element within product
Console.WriteLine("Product link text is {0}", product.<Link>.Value)
' output the value of the <Link> href attribute within product
Console.WriteLine("Product href is {0}", product.<Link>.@href)
Next
End Sub
End Module
Upvotes: 2