构建基于xml结构的html结构

时间:2011-11-27 22:16:59

标签: c# asp.net xml

我得到了以下xml:

<categories>
    <category>
        <id>1</id>
        <name>aaa</name>
                <url>lord</url>
        <categories>
            <category>
                <id>2</id>
                <name>bbb</name>
                                     <url>grrr</url>
            </category>
            <category>
                <id>3</id>
                <name>ccc</name>
                                     <url>grrr</url>
            </category>
        </categories>
    </category>
</categories>

我需要的是生成像:

这样的html
<ul>
 <li>
  <a href="url">aaa</a>
  <ul>
   <li><a href="url">bbb</a></li>
   <li><a href="url">ccc</a></li>
  </ul> 
 </li>
<ul>

任何提示?

ps:我可以在类别根目录中嵌套n个类别元素,并在每个类别中嵌套n个嵌套类别元素。

3 个答案:

答案 0 :(得分:3)

使用XSLT - 此答案不需要更长

答案 1 :(得分:3)

使用XSLT,这样的事情应该有效:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    exclude-result-prefixes="msxsl">
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="categories">
    <ul>
      <xsl:apply-templates select="category"/>
    </ul>
  </xsl:template>

  <xsl:template match="category">
    <li>
      <a>
        <xsl:attribute name="href"><xsl:value-of select="url"/></xsl:attribute>
        <xsl:value-of select="name"/>
      </a>
      <xsl:apply-templates select="categories"/>
    </li>
  </xsl:template>
</xsl:stylesheet>

哪个收益率:

<ul>
  <li><a href="lord">aaa</a><ul>
      <li><a href="grrr">bbb</a></li>
      <li><a href="grrr">ccc</a></li>
    </ul>
  </li>
</ul>

答案 2 :(得分:0)

首选方法可能是XSLT,但我非常偏爱LINQ-to-XML,因为我可以完全在代码中完成(没有引用或依赖于外部XSLT文档)。实际上我只是喜欢编写LINQ-to-XML而不是XSLT。

以下是将category节点投影到li节点

的示例
private XElement ConvertCategoryToListItem(XElement category)
{
    // new list item using the 'name' element
    var result = new XElement("li", category.Element("name").Value);

    // add any sub-categories to an ul element
    if (category.Element("categories") != null)
    {
        var nestedCategories = category.Element("categories").Elements("category");
        result.Add(new XElement("ul"), nestedCategories.Select(c => 
            ConvertCategoryToListItem(c)));
    }
    return result;
}

然后我会在原始XML中的所有类别上调用它​​。

new XElement("ul", this.input.Elements("category").Select(c => 
    ConvertCategoryToListItem(c)));