从XML获取列表节点的最大值

时间:2014-04-19 11:21:40

标签: asp.net xml vb.net xpath max

我使用的是Vb.net,我需要从以下XML中获取最大访问值。

<Pages>
<Page posted="2006-03-27" visits="148" title="Don't Sweep That Under the Rug!"/>
<Page posted="2006-07-12" visits="191" title="Tire Swings for Grownups"/>
<Page posted="2006-11-07" visits="214" title="Eliminate Hornets from Your Picnic"/>
<Page posted="2006-06-14" visits="296" title="Why Ants Invade Your Kitchen"/>
<Page posted="2006-01-15" visits="227" title="101 Ways to Climb a Tree"/>
<Page posted="2006-07-28" visits="133" title="The Beauty of a Frost-Free Refrigerator"/>
<Page posted="2006-03-31" visits="316" title="How to Achieve Restful Sleep"/>
<Page posted="2006-09-21" visits="232" title="Buying Your First Car"/>
</Pages>

我尝试使用以下代码,并且它运行正常。

    Dim Node As XmlNode = XmlDocumnet.SelectSingleNode("/Pages/Page/@visits[not(. <= ../preceding-sibling::Page/@visits) and not(. <=../following-sibling::Page/@visits)]")

    If Node IsNot Nothing AndAlso Node.Value <> "" Then
        MaxVisit= Convert.ToInt32(Node.Value) + 1
    End If

但是如果Visist属性具有重复值,那么它找不到正确的。 即,如果发现重复访问,则最大值不存在,也适用于空访问。

例如:

 <Page posted="2006-07-12" visits="214" title="Tire Swings for Grownups"/>
 <Page posted="2006-11-07" visits="214" title="Eliminate Hornets from Your Picnic"/>

或:

 <Page posted="2006-07-12" visits="" title="Tire Swings for Grownups"/>
 <Page posted="2006-11-07" visits="214" title="Eliminate Hornets from Your Picnic"/>

2 个答案:

答案 0 :(得分:1)

要返回第一个匹配项而不是没有结果,以防有多个节点具有最大visits,请将XPath更改为使用<而不是<=

/Pages/Page/@visits[
        not(. < ../preceding-sibling::Page/@visits) 
            and 
        not(. < ../following-sibling::Page/@visits)
        ]

更新:

除了XPath之外,还要过滤掉空visits,您可以尝试这种方式:

/Pages/Page/@visits[
        not(. < ../preceding-sibling::Page/@visits) 
            and 
        not(. < ../following-sibling::Page/@visits)
            and
        normalize-space(.)
        ]

答案 1 :(得分:1)

您可以使用以下Linq to Xml而不是使用XPath查询XmlDocument:

Dim el = XDocument.Parse(xmlInput)
Dim maxVisits = el.Descendants("Page") _
                  .Select(Function(x) New With { _
                                      .Title = x.Attribute("Title").Value, _
                                      .Visits = If(String.IsNullPrEmpty(x.Attribute.Value), 
                                                   0, 
                                                   Integer.Parse(x.Attribute("Visits").Value)) }) _
                  .OrderByDescending(Function(x) x.Visits) _
                  .FirstOrDefault()