背景:我们有项目需要使用golang语言解析rabbitmq.xml。并把里面的内容解析出来,但是在解析的时候遇到了问题,最后通过google搜索,在stackoverflow上找到了解决方案,目前好像没有中文的解决方案,所以就写下这篇博客,当其他的开发者遇到同样的问题时,可以方便排查,不走弯路。遇到无法解决的问题时请用Google,大概率还是可以找到解决方法的。
一、基础的解析XML方法
假如我们要解析如下的xml文件的内容:
<beans>
<queue id="myQueue" name="myQueue" durable="true" auto-delete="false" exclusive="false" />
</beans>
1. 首先是构造对应的struct对象
type Beans struct {
XMLName xml.Name `xml:"beans"`
RabbitQueues []RabbitQueue `xml:"queue"`
}
type RabbitQueue struct {
Name string `xml:"name,attr"`
Id string `xml:"id,attr"`
}
2. 调用golang里面的方法,将字符串转为struct对象。然后直接利用struct对象。
var beans Beans;
content,err := ioutil.ReadFile(path+"/"+file_name)
if err != nil {
fmt.Println(err)
}
xml.Unmarshal(content,&beans)
3. 这种情况解析一般都没什么问题,如果有不会可以搜索百度,有很多的回答。重点是介绍第二种情况
二、解析Tag带冒号的方法
1. 我们的项目需要解析的XML如下。和第一种会有区别在于<rabbit:queue> 这种tag里面是带了特殊符号( : )的。这种情况下直接构造struct并且是带:号的话,是解析会出错的。如(RabbitQueues []RabbitQueue `xml:"queue"`)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd" >
<rabbit:queue id="myQueue" name="myQueue" durable="true" auto-delete="false" exclusive="false" />
<rabbit:queue id="myQueue2" name="${xx.xxx.xx}" durable="true" auto-delete="false" exclusive="false" />
<!-- 定义监听器 -->
<rabbit:listener-container connection-factory="mqConnectionFactory" acknowledge="auto">
<rabbit:listener queues="myQueue" ref="queueListenter"/>
</rabbit:listener-container>
<rabbit:listener-container connection-factory="connectionFactory" >
<rabbit:listener queues="mq.asdf" ref="asdfConsumer"/>
</rabbit:listener-container>
</beans>
2. 正确的方法是,在struct构造的时候,加上namespace在前面就可以了。如下struct
重点看: RabbitQueues []RabbitQueue `xml:"http://www.springframework.org/schema/rabbit queue"`
type Beans struct {
XMLName xml.Name `xml:"beans"`
RabbitQueues []RabbitQueue `xml:"http://www.springframework.org/schema/rabbit queue"`
ListenerContainers []ListenerContainer `xml:"http://www.springframework.org/schema/rabbit listener-container"`
}
type RabbitQueue struct {
Name string `xml:"name,attr"`
Id string `xml:"id,attr"`
}
type ListenerContainer struct {
Listeners []RabbitListener `xml:"http://www.springframework.org/schema/rabbit listener"`
}
type RabbitListener struct {
Queues string `xml:"queues,attr"`
}
结尾:如果看完还是有问题。可以留言,看到后会帮你解决,或者去google golang parse xml tag : 等关键词。应该是可以找到解决方案的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)