I’m probably getting mad about it and there must be some trivial error in this. I’m trying to get from this XML code the “Value” attributes for each attribute Name == Eyes.
<?xml version="1.0" encoding="utf-8"?>
<Collection xmlns:p="http://schemas.microsoft.com/livelabs/pivot/collection/2009" SchemaVersion="1.0" Name="Actresses" xmlns="http://schemas.microsoft.com/collection/metadata/2009">
<FacetCategories>
<FacetCategory Name="Nationality" Type="LongString" p:IsFilterVisible="true" p:IsWordWheelVisible="true" p:IsMetaDataVisible="true" />
<FacetCategory Name="Eyes" Type="LongString" p:IsFilterVisible="true" p:IsWordWheelVisible="true" p:IsMetaDataVisible="true" />
</FacetCategories>
<Items ImgBase="Actresses_files\go144bwo.0ao.xml" HrefBase="http://www.imdb.com/name/">
<Item Id="0" Img="#0" Name="Virginie Ledoyen" Href="nm0001461/">
<Description> blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla </Description>
<Facets>
<Facet Name="Nationality">
<LongString Value="French" />
</Facet>
<Facet Name="Eyes">
<LongString Value="Blue" />
</Facet>
</Facets>
</Item>
<Item Id="1" Img="#1" Name="Meiko Kaji" Href="nm0435299/">
<Description> blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla blablabla </Description>
<Facets>
<Facet Name="Nationality">
<LongString Value="Japanese" />
</Facet>
<Facet Name="Eyes">
<LongString Value="Black" />
</Facet>
</Facets>
</Item>
</Items>
</Collection>
I need to populate a combobox with those attributes. My code is something like:
XNamespace fix = "http://schemas.microsoft.com/collection/metadata/2009";
IEnumerable<XElement> list2 =
from item in document.Descendants(fix + "Facet")
where (string)item.Attribute("Name") == "Eyes"
select item;
foreach (XElement x in list2)
{
this.comboBox2.Items.Add(x.Element("LongString").Attribute("Value").Value);
}
It turns out that the object is null before calling the method if I fix a watch on:
x.Element(“LongString”).Attribute(“Value”).Value;
I know it’s probably something I’m missing in traversing XML, but I don’t know why it turns out null, since if I try a dumb watch on (x.Value) then it’s not null.
The
LongStringelement is in thehttp://schemas.microsoft.com/collection/metadata/2009schema, so you need that as well:Basically, if there’s an
xmlns="..."attribute somewhere in the ancestry of an element, that’s taken as the default namespace for the element (with deeper ones overriding shallower ones).(Note that this defaulting doesn’t occur with attributes.)