xml - 去解析无效的 XML

标签 xml parsing go

有一个指向 XML 的链接:http://www.guru.com/rss/jobs/ 当尝试使用 encoding/xml 解析 XML 时,出现错误:

XML syntax error on line 1: invalid XML name: t

我知道,此 XML 已损坏,但我如何忽略它并解析第一项?

XML 的最后一项如下所示:

<item>
    <title>Online Ad Posting Data Entry Jobs</t
    <?xml version="1.0" encoding="utf-8"?>
    <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
        <channel>
            <title>Guru Jobs</title>
            <link>http://www.guru.com</link>
            <description>Guru Jobs</description>
            <lastBuildDate>Sun, 15 Nov 2015 11:04:51 GMT</lastBuildDate>
            <language>en-us</language>
            <atom:link href='http://www.guru.com/rss/jobs/' rel="self" type="application/rss+xml" />
        </channel>
    </rss>
    itle>
    <link>http://www.guru.com/jobs/online-ad-posting-data-entry-jobs/1189496</link>
    <guid>http://www.guru.com/jobs/online-ad-posting-data-entry-jobs/1189496</guid>
</item> 

代码示例:

type Rss2 struct { 
    ItemList []Item `xml:"channel>item"`
}
type Item struct {
    Title       string      `xml:"title"`
    Link        string      `xml:"link"`
    Description string      `xml:"description"`
    PubDate     string      `xml:"pubDate"`
    GUID        string      `xml:"guid"`    
}

r := Rss2{}
reader := bytes.NewReader(xmlRead)
decoder := xml.NewDecoder(reader)
decoder.CharsetReader = charset.NewReaderLabel
decoder.Strict = false
err = decoder.Decode(&r)
if err != nil { fmt.Printf(err.Error()) }

最佳答案

XML 标签应该正确打开和关闭。从您发布的 XML 来看,XML 声明似乎不在开始。

<?xml version="1.0" encoding="utf-8"?>

这应该在开头。希望这有帮助

关于xml - 去解析无效的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718880/

相关文章:

C# 在序列化/反序列化 XML 时更改列表中项目的元素名称

python - 如何使用 toprettyxml() 在同一行中给出 xml 标签和文本

ios - 从 XML/数组创建 map 图钉

c# - int.Parse() 和 ConvertTo.Int32() 之间的区别?

slice 类型的 Go-地道命名

android - 无法使用 android.support.v7.widget.AppCompatTextView 实例化以下类

c - 分析 ELF 部分和符号大小的工具

parsing - 如何使用 ANTLRv4 仅解析一些评论

go - 如何访问未转换的 driver.Value sql.Rows slice

go - 为什么Go中的位运算符比除法和模运算慢?