Linq-to-Xml,获取具有特定属性的元素

时间:2012-12-07 09:05:07

标签: vb.net linq

我有这个XML,

<MM>
    <Bank>
        <Result>
            <url>http://192.168.1.12/pay/api/abc</url>
            <param name="type">FUND</param>
            <param name="tid">175219</param>
            <param name="ticket">DiZfWMQxL5Qfasfsdfsdfsqweqwe</param>
            <param name="stage">1</param>
        <Result>
    <Bank>
</MM>

我知道如何获取url元素的值。

Dim qryurl = From c In doc.Descendants("Result") _
             Select c.Element("url").Value

如何从XML中标识param个标记值?

2 个答案:

答案 0 :(得分:0)

from x in c.Elements("param")
select new {
               type = x.Select(y => y.Attribute("name").Value == "type").Value,
               tid = x.Select(y => y.Attribute("name").Value == "tid").Value,
               ticket = x.Select(y => y.Attribute("name").Value == "ticket").Value,
               stage = x.Select(y => y.Attribute("name").Value == "stage").Value,

           }

可能存在一些语法错误。但这是获得价值的逻辑。您可以查看关于此主题的HERE

答案 1 :(得分:0)

我看看这样做:

Dim getParam As Func(Of XElement, String, String) =
    Function (e, t)
        Return e _
            .Elements("param") _
            .Where(Function (x) x.Attribute("name") = t) _
            .Select(Function (x) x.Value) _
            .FirstOrDefault()
    End Function

Dim Query = _
    From c In doc.Descendants("Result") _
    Select New With 
    { 
        .URL = c.Element("url").Value,
        .type = getParam(c, "type"),
        .tid = getParam(c, "tid"),
        .ticket = getParam(c, "ticket"),
        .stage = getParam(c, "stage")
    }

您当然可以将getParam函数直接扩展到查询中,但这会使它非常冗长。使用Func肯定会缩短它。

我给出上述代码和您的示例XML的结果是:

Query Result