I’m new to LINQ to XML and I have been looking at tutorials but I’ve not found one that has sufficient depth to get me past my block. In my case I hit a vendor of ours for information on a given address. There is the possibility that the address will not be an exact match so they send me back an XML file that has possible addresses.
Here is a given chunk of XML for a multiple list of addresses coming back from an address query:
<POSSIBLE-ADDRESSES>
<POS-ADDR>
<BUILDING>
<Street>1905 W HENDERSON RD </Street>
<City>COLUMBUS </City>
<RiskID>123456</RiskID>
</BUILDING>
<OCCUPANTS>
<OCCUP>
<ID>010</ID>
<Desc>MC DONALD'S RESTAURANT (1S) </Desc>
</OCCUP>
<OCCUP>
<ID>015</ID>
<Desc>MC DONALD'S RESTAURANT </Desc>
</OCCUP>
</OCCUPANTS>
</POS-ADDR>
<POS-ADDR>
<BUILDING>
<Street>1821 HENDERSON RD </Street>
<City>UPPER ARLINGTON </City>
<RiskID>1234567</RiskID>
</BUILDING>
<OCCUPANTS>
<OCCUP>
<ID>010</ID>
<Desc>ARLINGTON SQUARE SHOPPING CTR (1S) </Desc>
</OCCUP>
<OCCUP>
<ID>015</ID>
<Desc>1821 SWAN DRY CLNG </Desc>
</OCCUP>
<OCCUP>
<ID>020</ID>
<Desc>4681 ALEX'S BISTRO ON REED/REST </Desc>
</OCCUP>
<OCCUP>
<ID>025</ID>
<Desc>4687-93 BLUMEN GARTEN </Desc>
</OCCUP>
<OCCUP>
<ID>030</ID>
<Desc>4697 BLIMPIE/SANDWICH SHOP </Desc>
</OCCUP>
</OCCUPANTS>
</POS-ADDR>
</POSSIBLE-ADDRESSES>
Now what I do is pull all the buildings (mind you there can be many more than this) with the following and then bind that to a list box – no biggie:
var qBuildings = from LOP in loaded.Descendants("BUILDING")
select new
{
BuildingName = LOP.Element("Street").Value,
RiskId = LOP.Element("RiskID").Value
};
This gives me all the buildings that I need along with their risk ID’s.
Now the kicker is how to pull the “occupants” when the user selects a given building based on the risk ID say the first RiskID of “123456”. So if the user selects this building it will go out and grab each occupant hydrating an occupant class and add that class to a list of occupants which I will then bind to another list box.
Everything I’ve tried so far has had bad results at just trying to get the occupants. I know it must be a matter of navigation but I can’t seem to build the query in a way that returns anything useful. Each risk ID is unique and each building can have none or many occupants. So I’m lost at how to pull the occupants.
Any help would be appreciated.
It seems to me you want to select occupants from a pos-addr, whose building has a specific riskId. In LINQ-to-XML, that could look like this: