Wallace
Wallace

Reputation: 580

Linq xml query with arguments

My goal is to create a query, for an XDocument, that only returns the strikePrice's value if the correct date is located in the attribute symbol.

The symbol, in the example XDocument, has a ticker AAPL, date 131221, type C and it ends with a variable number of digits.

Example XDocument:

<query>
    <results>
        <optionsChain>
            <option symbol="AAPL131221C00245000" type="C">    
                <strikePrice>245</strikePrice>
                <lastPrice>299.04</lastPrice>
                <change>0</change>
                <changeDir/>
                <bid>314.1</bid>
                <ask>317</ask>
                <vol>1</vol>
                <openInt>5</openInt>
            <option/>
        <optionChain/>
        <optionsChain>
        ....
        <optionsChain/>
    <results/>
<query/>

I can retrieve the date from the symbol's string with the following code:

string startingString = "AAPL";
string symbol = "AAPL131221C0024500";

string date = symbol.Substring(startingString.Length, 6))

I can retrieve ALL the strikes with the following query:

XDocument Doc = Example XDocument;
List<string> list = new List<string>();
        list = Doc.Descendants("results")
                .Descendants("optionsChain")
                .Descendants("option")
                .Elements("strikePrice")
                .Select(d => d.Value)
                .ToList();

How can I combine the two and build a query that ONLY returns strikePrice values if the correct date is located in the attribute symbol?

Upvotes: 0

Views: 64

Answers (1)

Sico
Sico

Reputation: 1183

How about using XPath instead and querying the values that way.

var nodes = doc.SelectNodes("//query/results/optionsChain/option[starts-with(@symbol, '--lookup value--')]/StrikePrice");

Haven't tested the above but is useful for XmlDocument.

Here is an example of using this with XPathEvaluate on an XDocument http://msdn.microsoft.com/en-us/library/bb675197.aspx

Upvotes: 1

Related Questions