猿问

如何从 XML 字符串中删除 XML 意图。?

我有一个 XML 字符串。我无法从 XML 字符串中删除缩进空间。我更换了换行符。


  <person id="13">

      <name>

          <first>John</first>

          <last>Doe</last>

      </name>

      <age>42</age>

      <Married>false</Married>

      <City>Hanga Roa</City>

      <State>Easter Island</State>

      <!-- Need more details. -->

  </person>

如何从 GOLANG 中的字符串中删除 XML 缩进空格?


我希望这个 XML 像字符串一样,


<person id="13"><name><first>John</first><last>Doe</last></name><age>42</age><Married>false</Married><City>Hanga Roa</City><State>Easter Island</State><!-- Need more details. --></person>

如何在 GOLANG 中做到这一点?


森林海
浏览 154回答 3
3回答

Smart猫小萌

一些背景不幸的是,XML 不是一种正则语言,因此您根本无法使用正则表达式可靠地处理它——无论您能想出多么复杂的正则表达式。我会从这个问题的精彩幽默开始,然后阅读,比如说,这个。为了演示,对您的示例进行一个简单的更改会破坏您的处理,例如,这可能是:&nbsp; <person id="13">&nbsp; &nbsp; &nbsp; <name>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <first>John</first>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <last>Doe</last>&nbsp; &nbsp; &nbsp; </name>&nbsp; &nbsp; &nbsp; <age>42</age>&nbsp; &nbsp; &nbsp; <Married>false</Married>&nbsp; &nbsp; &nbsp; <City><![CDATA[Hanga <<Roa>>]]></City>&nbsp; &nbsp; &nbsp; <State>Easter Island</State>&nbsp; &nbsp; &nbsp; <!-- Need more details. -->&nbsp; </person>其实考虑到这个<last>VonNeumann</last>为什么您认为您可以自由地从该元素的内容中删除换行符?当然,你会说一个人不能明智地在他们的姓氏中使用换行符。好的,但是这个呢?<poem author="Chauser">&nbsp; <strophe number="1">&nbsp; The lyf so short,&nbsp; the craft so long to lerne.</strophe></poem>您不能明智地删除该句子的两个部分之间的空格 - 因为这是作者的意图。好吧,完整的故事在 XML 规范的“空白处理”部分中定义。外行人尝试在 XML 中描述空白处理如下:XML 规范本身并没有为空白指定任何特殊含义:关于空白在XML 文档的特定位置中的含义的决定取决于该文档的处理器。通过扩展,该规范不强制任何“标签”(那些<foo>和</bar>和<quux/>事物 - 出现在允许 XML 标记的点)之间的空白是否重要:只有您自己决定。为了更好地理解其原因,请考虑以下文档:<p>␣Some&nbsp;text&nbsp;which&nbsp;contains&nbsp;an␣<em>emphasized&nbsp;block</em>which&nbsp;is&nbsp;followed&nbsp;by&nbsp;a&nbsp;linebreak&nbsp;and&nbsp;more&nbsp;text.</p>这是一个完全有效的 XML,出于显示目的,我已将标记之后和<p>标记之前的空格字符替换<em>为 Unicode“打开框”字符。请注意,整个文本␣Some text which contains an␣出现在两个标签之间,并且包含明显重要的前导和尾随空格- 如果不是,则强调的文本(用 标记的文本<em>…</em>将与前面的文本粘合在一起)。</em>相同的逻辑适用于标签后的换行符和更多文本。XML 规范暗示将“无关紧要”的空白定义为表示一对相邻标签之间的任何空白可能很方便,这些标签不定义单个元素。XML 还有两个使处理更加复杂的特征:字符实体(那些&amp;和&lt;事物)允许直接插入任何 Unicode 代码点:例如,&#x000d;将插入换行符。XML 支持特殊的“CDATA 部分”,您的解析器表面上对此一无所知。解决方法在我们尝试提出解决方案之前,我们将定义我们打算将哪些空白视为无关紧要并丢弃。看起来像您的文档类型,定义应该是:任何两个标签之间的任何字符数据都应该被删除,除非:它至少包含一个非空白字符,或它完全定义了单个 XML 元素的内容。考虑到这些考虑,我们可以编写代码,将输入 XML 流解析为令牌并将它们写入输出 XML 流,同时应用以下逻辑来处理令牌:如果它看到除字符数据之外的任何 XML 元素,它会将它们编码到输出流中。此外,如果该元素是一个开始标签,它会通过设置一些标志来记住这一事实;否则标志被清除。如果它看到任何字符数据,它会检查该字符数据是否紧跟在开始元素(开始标记)之后,如果是,则保存该字符数据块。当已经存在这样的已保存块时,也会保存字符数据块——这是必需的,因为在 XML 中,文档中可能有几个相邻但仍然不同的字符数据块。如果它看到任何 XML 元素,并检测到它有一个或多个保存的字符块,那么它首先决定是否将它们放入输出流:如果元素是结束元素(结束标记),则所有字符数据块都必须“按原样”放入输出流中——因为它们完全定义了单个元素的内容。否则,如果至少一个已保存的字符数据块包含至少一个非空白字符,则所有块都按原样写入输出流。否则将跳过所有块。这是实现所描述方法的工作代码:package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "errors"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "os"&nbsp; &nbsp; "strings")const xmlData = `<?xml version="1.0" encoding="utf-8"?>&nbsp; <person id="13">&nbsp; &nbsp; &nbsp; weird text&nbsp; &nbsp; &nbsp; <name>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <first>John</first>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <last><![CDATA[Johnson & ]]><![CDATA[ <<Johnson>> ]]><![CDATA[ & Doe ]]></last>&nbsp; &nbsp; &nbsp; </name>&#x000d;&#x0020;&#x000a;&#x0009;<age>&nbsp; &nbsp; &nbsp; 42&nbsp; &nbsp; &nbsp; </age>&nbsp; &nbsp; &nbsp; <Married>false</Married>&nbsp; &nbsp; &nbsp; <City><![CDATA[Hanga <Roa>]]></City>&nbsp; &nbsp; &nbsp; <State>Easter Island</State>&nbsp; &nbsp; &nbsp; <!-- Need more details. --> what?&nbsp; &nbsp; &nbsp; <foo> more <bar/> text </foo>&nbsp; </person>`func main() {&nbsp; &nbsp; stripped, err := removeWS(xmlData)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintln(os.Stderr, err)&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Print(stripped)}func removeWS(s string) (string, error) {&nbsp; &nbsp; dec := xml.NewDecoder(strings.NewReader(s))&nbsp; &nbsp; var sb strings.Builder&nbsp; &nbsp; enc := NewSkipWSEncoder(&sb)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; tok, err := dec.Token()&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err == io.EOF {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "", fmt.Errorf("failed to decode token: %w", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; err = enc.EncodeToken(tok)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "", fmt.Errorf("failed to encode token: %w", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; err := enc.Flush()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return "", fmt.Errorf("failed to flush encoder: %w", err)&nbsp; &nbsp; }&nbsp; &nbsp; return sb.String(), nil}type SkipWSEncoder struct {&nbsp; &nbsp; *xml.Encoder&nbsp; &nbsp; sawStartElement bool&nbsp; &nbsp; charData&nbsp; &nbsp; &nbsp; &nbsp; []xml.CharData}func NewSkipWSEncoder(w io.Writer) *SkipWSEncoder {&nbsp; &nbsp; return &SkipWSEncoder{&nbsp; &nbsp; &nbsp; &nbsp; Encoder: xml.NewEncoder(w),&nbsp; &nbsp; }}func (swe *SkipWSEncoder) EncodeToken(tok xml.Token) error {&nbsp; &nbsp; if cd, isCData := tok.(xml.CharData); isCData {&nbsp; &nbsp; &nbsp; &nbsp; if len(swe.charData) > 0 || swe.sawStartElement {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; swe.charData = append(swe.charData, cd.Copy())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if isWS(cd) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return swe.Encoder.EncodeToken(tok)&nbsp; &nbsp; }&nbsp; &nbsp; if len(swe.charData) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; _, isEndElement := tok.(xml.EndElement)&nbsp; &nbsp; &nbsp; &nbsp; err := swe.flushSavedCharData(isEndElement)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; _, swe.sawStartElement = tok.(xml.StartElement)&nbsp; &nbsp; return swe.Encoder.EncodeToken(tok)}func (swe *SkipWSEncoder) Flush() error {&nbsp; &nbsp; if len(swe.charData) > 0 {&nbsp; &nbsp; &nbsp; &nbsp; return errors.New("attempt to flush encoder while having pending cdata")&nbsp; &nbsp; }&nbsp; &nbsp; return swe.Encoder.Flush()}func (swe *SkipWSEncoder) flushSavedCharData(mustKeep bool) error {&nbsp; &nbsp; if mustKeep || !allIsWS(swe.charData) {&nbsp; &nbsp; &nbsp; &nbsp; err := encodeCDataList(swe.Encoder, swe.charData)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; swe.charData = swe.charData[:0]&nbsp; &nbsp; return nil}func encodeCDataList(enc *xml.Encoder, cdataList []xml.CharData) error {&nbsp; &nbsp; for _, cd := range cdataList {&nbsp; &nbsp; &nbsp; &nbsp; err := enc.EncodeToken(cd)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return nil}func isWS(b []byte) bool {&nbsp; &nbsp; for _, c := range b {&nbsp; &nbsp; &nbsp; &nbsp; switch c {&nbsp; &nbsp; &nbsp; &nbsp; case 0x20, 0x09, 0x0d, 0x0a:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; return true}func allIsWS(cdataList []xml.CharData) bool {&nbsp; &nbsp; for _, cd := range cdataList {&nbsp; &nbsp; &nbsp; &nbsp; if !isWS(cd) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true}游乐场。我不确定它是否完全涵盖了所有可能的奇怪情况,但它应该是一个好的开始。

aluckdog

删除 XML 标记之间的纯空格序列func unformatXML(xmlString string) string {&nbsp; &nbsp; var unformatXMLRegEx = regexp.MustCompile(`>\s+<`)&nbsp; &nbsp; unformatBetweenTags := unformatXMLRegEx.ReplaceAllString(xmlString, "><") // remove whitespace between XML tags&nbsp; &nbsp; return strings.TrimSpace(unformatBetweenTags) // remove whitespace before and after XML}正则表达式解释\s - 匹配任何空格,包括制表符、换行符、换页符、回车符和空格+ - 匹配一个或多个空白字符正则表达式语法参考:https ://golang.org/pkg/regexp/syntax/例子package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "regexp"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; var s = `&nbsp; &nbsp;&nbsp;<person id="13">&nbsp; &nbsp; <name>&nbsp; &nbsp; &nbsp; &nbsp; <first>John</first>&nbsp; &nbsp; &nbsp; &nbsp; <last>Doe</last>&nbsp; &nbsp; </name>&nbsp; &nbsp; <age>42</age>&nbsp; &nbsp; <Married>false</Married>&nbsp; &nbsp; <City>Hanga Roa</City>&nbsp; &nbsp; <State>Easter Island</State>&nbsp; &nbsp; <!-- Need more details. --></person>&nbsp; &nbsp;`&nbsp; &nbsp; s = unformatXML(s)&nbsp; &nbsp; fmt.Println(fmt.Sprintf("'%s'", s)) // single quotes used to confirm no leading or trailing whitespace}func unformatXML(xmlString string) string {&nbsp; &nbsp; var unformatXMLRegEx = regexp.MustCompile(`>\s+<`)&nbsp; &nbsp; unformatBetweenTags := unformatXMLRegEx.ReplaceAllString(xmlString, "><") // remove whitespace between XML tags&nbsp; &nbsp; return strings.TrimSpace(unformatBetweenTags) // remove whitespace before and after XML}Go Playground 中的可运行示例https://play.golang.org/p/VS1LRNevicz

斯蒂芬大帝

首先需要从 XML 中删除缩进,然后需要删除换行符。// Regex to remove indentationm1 := regexp.MustCompile(`( *)<`)newstr := m1.ReplaceAllString(xmlString, "<")// Replace newlinenewLineReplacer := strings.NewReplacer("\n", "", "\r\n", "")xmlString = newLineReplacer.Replace(newstr)在这里找到这个,https://play.golang.org/p/Orp2RyPbGP2
随时随地看视频慕课网APP

相关分类

Go
我要回答