在Python、PHP和许多其他语言中,可以将HTML文档转换并“美化”。在Go中,可以使用MarshIndent函数非常轻松地对JSON和XML(从结构/接口)进行此操作。
Go中XML的示例:
然而,这只适用于将struct/interface转换为[]byte。我想要的是将一段HTML代码字符串自动缩进。例如:
原始HTML
美化后的HTML
Go中XML的示例:
http://play.golang.org/p/aBNfNxTEG1
package main
import (
"encoding/xml"
"fmt"
"os"
)
func main() {
type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
}
v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
v.Comment = " Need more details. "
v.Address = Address{"Hanga Roa", "Easter Island"}
output, err := xml.MarshalIndent(v, " ", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
os.Stdout.Write(output)
}
然而,这只适用于将struct/interface转换为[]byte。我想要的是将一段HTML代码字符串自动缩进。例如:
原始HTML
<!doctype html><html><head>
<title>Website Title</title>
</head><body>
<div class="random-class">
<h1>I like pie</h1><p>It's true!</p></div>
</body></html>
美化后的HTML
<!doctype html>
<html>
<head>
<title>Website Title</title>
</head>
<body>
<div class="random-class">
<h1>I like pie</h1>
<p>It's true!</p>
</div>
</body>
</html>
如何仅使用字符串实现此操作?