如何用两次手动调用替换简单的两匝循环

这是代码: https: //play.golang.org/p/Sizbc3uJt_c

我尝试替换这个简单的循环

for c := n.FirstChild; c != nil; c = c.NextSibling {

    indent(space+"   ", c)

}

产生


html

   head

   body

      a

         1

      a

         1

      div

         a

            2

         a

            3

当我尝试这个时


if n.FirstChild != nil {

    indent(space+"   ", n.FirstChild)

}

if n.FirstChild != nil && n.FirstChild.NextSibling != nil {

    indent(space+"   ", n.FirstChild.NextSibling)

}

输出只有一半


html

   head

   body

      a

         1

      a

         1

当我尝试这个时


if n.FirstChild != nil {

    indent(space+"   ", n.FirstChild)

}

if n.NextSibling != nil {

    indent(space+"   ", n.NextSibling)

}

输出已完成,但缩进不同。结果是


html

   head

      body

         a

            1

            a

               1

               div

                  a

                     2

                     a

                        3


哈士奇WWW
浏览 73回答 1
1回答

白板的微信

如果您想使用您建议的具有奇怪缩进的第二组代码,那么解决方案如下:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "strings"&nbsp; &nbsp; "golang.org/x/net/html")func main() {&nbsp; &nbsp; r := strings.NewReader(`<a href="test1.html">1</a><a href="test1.html">1</a><div><a href="test2.html">2</a><a href="test3.html">3</a></div>`)&nbsp; &nbsp; doc, err := html.Parse(r)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalln(err)&nbsp; &nbsp; }&nbsp; &nbsp; indent("", doc)}func indent(space string, n *html.Node) {&nbsp; &nbsp; fmt.Println(space, n.Data)&nbsp; &nbsp; if n.FirstChild != nil {&nbsp; &nbsp; &nbsp; &nbsp; indent(space+"&nbsp; &nbsp;", n.FirstChild)&nbsp; &nbsp; }&nbsp; &nbsp; if n.NextSibling != nil {&nbsp; &nbsp; &nbsp; &nbsp; indent(space, n.NextSibling)&nbsp; &nbsp; }}您只需删除+"&nbsp; &nbsp; "缩进调用的额外内容n.NextSibling,以便同级节点不会比其先前的同级节点被推出得更远。
打开App,查看更多内容
随时随地看视频慕课网APP