XML看起来像这样:
<?xml version="1.0" encoding="UTF-8" ?>
<nodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<element>Content1</element>
<element>Content2</element>
<element>Content3</element>
<parent>
<element>Content4</element>
<element>Content5</element>
<parent>
<element>Content6</element>
<parent>
<element>Content7</element>
<element>Content8</element>
</parent>
<element>Content9</element>
</parent>
<element>Content10</element>
<element>Content11</element>
</parent>
<element>Content12</element>
<parent>
<element>Content13</element>
<element>Content14</element>
</parent>
<element>Content15</element>
</nodes>
我想选择所有称为元素的节点,如果它们在父节点内,我想知道它们有多少父元素,所以我可以在html中显示这个html结构,如下所示:
<pre>
Content1
Content2
Content3
Content4
Content5
Content6
Content7
Content8
Content9
Content10
Content11
Content12
Content13
Content14
Content15
</pre>
有什么想法吗?
答案 0 :(得分:0)
我可以用c#
来做using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
"<nodes xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<element>Content1</element>" +
"<element>Content2</element>" +
"<element>Content3</element>" +
"<parent>" +
"<element>Content4</element>" +
"<element>Content5</element>" +
"<parent>" +
"<element>Content6</element>" +
"<parent>" +
"<element>Content7</element>" +
"<element>Content8</element>" +
"</parent>" +
"<element>Content9</element>" +
"</parent>" +
"<element>Content10</element>" +
"<element>Content11</element>" +
"</parent>" +
"<element>Content12</element>" +
"<parent>" +
"<element>Content13</element>" +
"<element>Content14</element>" +
"</parent>" +
"<element>Content15</element>" +
"</nodes>";
XDocument doc = XDocument.Parse(input);
string output = "<pre>\n";
XElement nodes = doc.Element("nodes");
int level = 0;
GetChild(ref output, nodes, level);
output += "</pre>\n";
}
static void GetChild(ref string output, XElement nodes, int level)
{
foreach (XElement element in nodes.Elements())
{
switch(element.Name.ToString())
{
case "parent" :
GetChild(ref output, element, level + 1);
break;
case "element" :
output += new string(' ',4 * level) + element.Value + "\n";
break;
}
}
}
}
}
答案 1 :(得分:0)
在XSL中执行此操作的正确代码是:
<pre>
<xsl:for-each select="//element">
<xsl:for-each select="ancestor::parent">
<xsl:text>	</xsl:text>
</xsl:for-each>
<xsl:value-of select="." />
</xsl:for-each>
</pre>
说明:
答案 2 :(得分:-1)
很难准确回答没有xslt样本,但在这里我可以给你一个原始答案:
<xsl:template match="element">
<xsl:variable name="parentsCount" select="ancestor::parent"/>
... here what you want to do, and you can use the $parentsCount variable....
</xsl:template>