【问题标题】:XPath expression to get count of the child elementsXPath 表达式以获取子元素的计数
【发布时间】:2016-12-02 22:35:03
【问题描述】:

我有一个这样的 XML

<Root>
   <Mgr name="X">
       <Emp name = "X1"/>
       <Emp name = "X2"/>
       <Emp name = "X3"/>
   </Mgr>
   <Mgr name="Y">
       <Emp name = "Y1"/>
       <Emp name = "Y2"/>
   </Mgr>
</Root>

我可以使用 count(/Root/Mgr/Emp) 轻松获得员工总数,但我希望获得每位经理的人数。
像这样的东西 - '3,2'。

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    XPath 1.0

    这个 XPath 1.0 表达式,

    concat(count(/Root/Mgr[1]/Emp), ',', count(/Root/Mgr[2]/Emp))
    

    会回来

    3,2
    

    根据要求用于您的 XML。

    XPath 2.0

    这个 XPath 2.0 表达式,

    string-join(/root/Mgr/count(Emp), ',')
    

    会回来

    3,2
    

    根据要求用于您的 XML(并且很好地概括了两个 Mgr 元素之外)。

    【讨论】:

    • 它肯定适用于您的 XSLT-2.0 解决方案,但是对于两个以上的 Mgr 节点,XPath-1.0 解决方案会是什么样子呢? (我相信这将不胜感激)
    • @zx485:要在 XPath 1.0 中获得与 XPath 2.0 一样通用的解决方案,需要调用 XPath 库的语言的帮助。
    • 是这样想的。感谢您的肯定。
    • @kjhughes - 我得到 Error:DOMXPath::evaluate(): Invalid expression when I try string-join(/root/Mgr/count(Emp), ',') in an online xpath evaluator .
    • @Fox:该错误暗示该 XPath 评估程序不支持 XPath 2.0。
    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多