如何使用字符串分词器替换特定的 html 标签

How to replace specific html tags using string tokenizer

我有一个带有 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 文本中的一些节点。对于此类任务,使用 DOMs(文档对象模型)比自己处理标记要容易得多。

您正在使用的包 golang.org/x/net/html also supports modeling HTML documents using the html.Node type. To acquire the DOM of an HTML document, use the html.Parse() 功能。

所以你应该做的是遍历[=​​56=],并替换(修改)你想要的节点。完成修改后,您可以通过渲染 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 包添加了包装器 <html><body> 元素,以及一个空的 <head> .

如果你想摆脱这些,你可以只渲染 <body> 元素的内容而不是整个 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 as the output for rendering, and call its 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.

上试试