-1

How to parse through XML file using a node Id. I want to get to <Rate>0.8988</Rate> node of <rate id="USDEUR">

<results>
    <rate id="USDEUR">
    <Name>USD/EUR</Name>
    <Rate>0.8988</Rate>
    <Date>5/27/2016</Date>
    <Time>6:56pm</Time>
    <Ask>0.8989</Ask>
    <Bid>0.8988</Bid>
    </rate>
    <rate id="USDJPY">
    <Name>USD/JPY</Name>
    <Rate>110.1250</Rate>
    <Date>5/27/2016</Date>
    <Time>6:53pm</Time>
    <Ask>110.1500</Ask>
    <Bid>110.1250</Bid>
    </rate>
    </results>

This is what I am able to do so far.

string sitemapurl = @"http://example.com/xmlforexrates";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(sitemapurl);
XmlNodeList nodeIds = xmlDoc.SelectNodes("/results/rate");

Right now it's getting all the <rate> nodes in the NodeList. I just wanted to get node on Id based for example only <rate id="USDEUR">

Please help me do this. Thanks

aadi1295
  • 982
  • 3
  • 19
  • 47
  • 2
    I think you got this upside down. You have to write some code first. If that doesn't work, then you post your code here, and ask a specific question about it to get help. – sstan May 27 '16 at 19:05
  • just updated my question, please remove negative marking. Thanks – aadi1295 May 27 '16 at 19:10
  • 1
    http://stackoverflow.com/questions/19786770/how-can-i-get-a-node-by-id-in-xml – Tim Freese May 27 '16 at 19:13

2 Answers2

0

Using XPath, you can do it like this:

XmlNodeList nodeIds = xmlDoc.SelectNodes("/results/rate[@id='USDEUR']/Rate/text()");
sstan
  • 35,425
  • 6
  • 48
  • 66
0

This is pretty trivial using LINQ to XML.

var doc = XDocument.Load("http://example.com/xmlforexrates");

var rate = (decimal)doc
    .Descendants("rate")
    .Where(x => (string) x.Attribute("id") == "USDEUR")
    .Elements("Rate")
    .Single();

See this fiddle for a working demo.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45