0

我的 XML 如下所示

<Exchange>
    <Rec>
        <data headers="Currency">USD</data>
        <data headers="Value">1.0609</data>
    </Rec>
    <Rec>
        <data headers="Currency">GBP</data>
        <data headers="Value">0.6694</data>
    </Rec>
    <Rec>
        <data headers="Currency">INR</data>
        <data headers="Value">54.123</data>
    </Rec>
</Exchange>

我必须在 asp.net 中使用 XML Linq 检索值(1.0609)取决于货币(美元)

4

2 回答 2

0
var xml = XElement.Load("XMLFile1.xml");

string curr = "USD";
var number = (from node in xml.Elements("Rec").Elements("data")
    where (string)node.Attribute("headers") == "Currency" && node.Value == curr
    select node into data
    from value in data.Parent.Elements("data")
    where (string)value.Attribute("headers") == "Value"
    select (double)value).FirstOrDefault();
于 2012-04-13T15:21:22.850 回答
0

这是一种方法。虽然不是特别优雅。

var doc = XDocument.Load(@"<path>\exchange.xml");

// convert xml to List<> containing Currency and Value
var q = doc.Element("Exchange").Elements("Rec").Select (e => 
    new {
        Currency = e.Elements("data").
                Where (x => "Currency" == (string) x.Attribute("headers")).
                Select (x => (string)x).Single (),

        Value = e.Elements("data").
                Where (x => "Value" == (string) x.Attribute("headers")).
                Select (x => (double)x).Single (),
    }
);

// select the value we're after
var q1 = q.Where (x => x.Currency == "USD").Select (x => x.Value).Single ();

q1.Dump();
于 2012-04-12T11:28:47.220 回答