首页 > 解决方案 > XSLT创建一个变量来计算for-each中的迭代次数

问题描述

我不知道如何创建变量和 assi。

我是使用 XSLT 的新手,我有一个 XML 文件,该文件有一些节点,节点有一些子节点我需要使用 for-each 来计算这些子节点(每个 for-each 我需要将该计数增加 1 以及我的计数器我想从1开始)

我不知道如何创建一个变量并将其分配给值 1。

这是我需要的示例:

<root>
  <body>
    <sec id="sec1">
      <!--Parent also can contain no sub element or also can contain a free text-->
      <p></p>
      <p>some free text</p>
      <p>
        <!--Nodes I want to count it-->
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <!--Nodes I want to count it-->
      </p>
    </sec>
    <sec id="sec2">
      <p>
        <!--Nodes I want to count it-->
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <!--Nodes I want to count it-->
      </p>
      <p>
        <!--Nodes I want to count it-->
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <childNodes></childNodes>
        <!--Nodes I want to count it-->
      </p>
    </sec>
  </body>
</root>

我需要这样的输出

<root>
    <childNodes>
        <count> 
            The count of all childNodes
        </count>
    </childNodes>
</root>

你能帮忙解决这个问题吗,在此先感谢

标签: c#xmlxslt

解决方案


使用 xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication58
{
    class Program
    {
        static void Main(string[] args)
        {
            XElement root = new XElement("root");
            XElement body = new XElement("body");
            root.Add(body);


            for (int id = 1; id <= 10; id++)
            {
                XElement newSec = new XElement("sec",
                    new XAttribute("id", "sec" + id.ToString()),
                    XElement.Parse("<!--Parent also can contain no sub element or also can contain a free text--><p></p>"),
                    new XElement("p", "some free text")
                    );
                body.Add(newSec);
                XElement nodes = new XElement("p");
                newSec.Add(nodes);

                for (int childCount = 1; childCount <= 10; childCount++)
                {
                    XElement newChild = new XElement("childNods", new XAttribute("id", "node" + childCount.ToString()),
                        "Child Text"
                     );
                    nodes.Add(newChild);

                }

            }


        }

    }
}

推荐阅读