登录
首页 >  Golang >  Go问答

使用字符串解析器替换特定 HTML 标记的方法

来源:stackoverflow

时间:2024-02-22 16:48:26 332浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《使用字符串解析器替换特定 HTML 标记的方法》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有一个带有 html 标记的字符串(differmarkup),并且希望通过标记生成器运行该字符串,该标记生成器将识别特定标记(如 ins、dels、movs)并将其替换为 span 标记并将数据属性添加到也是如此。

所以输入看起来像这样:

`<h1>no changes here</h1>
    <p>this has no changes</p>
    <p id="1"><del>delete </del>the first word</p>
    <p id="2"><ins>insertion </ins>insert a word at the start</p>`

预期的输出是这样的:

`<h1>no changes here</h1>
    <p>this has no changes</p>
    <p id="1"><span class="del" data-cid=1>delete</span>the first word</p>
    <p id="2"><span class="ins" data-cid=2>insertion</span>insert a word at the start</p>
`

这就是我目前拥有的。由于某种原因,在将其设置为 span 时,我无法将 html 标签附加到 finalmarkup var。

const (
    htmlTagStart = 60 // Unicode `<`
    htmlTagEnd   = 62 // Unicode `>`
    differMarkup = `<h1>No Changes Here</h1>
    <p>This has no changes</p>
    <p id="1"><del>Delete </del>the first word</p>
    <p id="2"><ins>insertion </ins>Insert a word at the start</p>`  // Differ Markup Output
)

func readDifferOutput(differMarkup string) string {

    finalMarkup := ""
    tokenizer := html.NewTokenizer(strings.NewReader(differMarkup))
    token := tokenizer.Token()
loopDomTest:
    for {
        tt := tokenizer.Next()
        switch {

        case tt == html.ErrorToken:
            break loopDomTest // End of the document,  done

        case tt == html.StartTagToken, tt == html.SelfClosingTagToken:
            token = tokenizer.Token()
            tag := token.Data

            if tag == "del" {
                tokenType := tokenizer.Next()

                if tokenType == html.TextToken {
                    tag = "span"
                    finalMarkup += tag
                }

                //And add data attributes
            }

        case tt == html.TextToken:
            if token.Data == "span" {
                continue
            }
            TxtContent := strings.TrimSpace(html.UnescapeString(string(tokenizer.Text())))
            finalMarkup += TxtContent
            if len(TxtContent) > 0 {
                fmt.Printf("%s\n", TxtContent)
            }
        }
    }

    fmt.Println("tokenizer text: ", finalMarkup)

    return finalMarkup

}
```golang

解决方案


基本上,您想要替换 html 文本中的某些节点。对于此类任务,使用 dom(文档对象模型)比自己处理标记要容易得多。

您使用的包 golang.org/x/net/html 还支持使用 html.Node 类型对 html 文档进行建模。要获取 html 文档的 dom,请使用 html.Parse() 函数。

所以你应该做的是遍历 dom,并替换(修改)你想要的节点。完成修改后,您可以通过渲染 dom 取回 html 文本,为此使用 html.Render()

这是可以做到的:

const src = `<h1>no changes here</h1>
<p>this has no changes</p>
<p id="1"><del>delete </del>the first word</p>
<p id="2"><ins>insertion </ins>insert a word at the start</p>`

func main() {
    root, err := html.parse(strings.newreader(src))
    if err != nil {
        panic(err)
    }

    replace(root)

    if err = html.render(os.stdout, root); err != nil {
        panic(err)
    }
}

func replace(n *html.node) {
    if n.type == html.elementnode {
        if n.data == "del" || n.data == "ins" {
            n.attr = []html.attribute{{key: "class", val: n.data}}
            n.data = "span"
        }
    }

    for child := n.firstchild; child != nil; child = child.nextsibling {
        replace(child)
    }
}

这将输出:

<html><head></head><body><h1>no changes here</h1>
<p>this has no changes</p>
<p id="1"><span class="del">delete </span>the first word</p>
<p id="2"><span class="ins">insertion </span>insert a word at the start</p></body></html>

这几乎就是你想要的,“额外”的事情是 html 包添加了包装器 元素,以及一个空的 zqbendczq b.

如果你想摆脱这些,你可以只渲染 元素的内容,而不是整个 dom:

// to navigate to the <body> node:
body := root.firstchild. // this is <html>
                firstchild. // this is <head>
                nextsibling // this is <body>
// render everyting in <body>
for child := body.firstchild; child != nil; child = child.nextsibling {
    if err = html.render(os.stdout, child); err != nil {
        panic(err)
    }
}

这将输出:

<h1>no changes here</h1>
<p>this has no changes</p>
<p id="1"><span class="del">delete </span>the first word</p>
<p id="2"><span class="ins">insertion </span>insert a word at the start</p>

我们就完成了。尝试 Go Playground 上的示例。

如果您希望结果为 string(而不是打印到标准输出),您可以使用 bytes.Buffer 作为输出进行渲染,并在最后调用其 Buffer.String() 方法:

// Render everyting in <body>
buf := &bytes.Buffer{}
for child := body.FirstChild; child != nil; child = child.NextSibling {
    if err = html.Render(buf, child); err != nil {
        panic(err)
    }
}

fmt.Println(buf.String())

这输出相同。在Go Playground上尝试一下。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>