【发布时间】:2011-10-18 12:39:17
【问题描述】:
我正在尝试使用 XmlSlurper 解析 google atom。我的用例是这样的。
1) 将 atom xml 发送到带有 rest 客户端的服务器。
2)在服务器端处理请求并解析它。
我使用 Groovy 开发我的服务器并使用 XmlSlurper 作为解析器。但我无法成功并得到“prolog 中不允许的内容”异常。然后我试图找出它发生的原因。我将 atom xml 保存到使用 utf-8 编码的文件中。然后尝试读取文件并解析原子,我得到了同样的异常。但后来我将 atom xml 保存到一个文件 whixh 用 ansi 编码。我成功地解析了atom xml。所以我认为问题在于 XmlSlurper 和“UTF-8”。
您对此限制有任何想法吗?我的 atom xml 必须是 utf-8,那么我该如何解析这个 atom xml 呢?感谢您的帮助。
XML:
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:atom='http://www.w3.org/2005/Atom'
xmlns:gd='http://schemas.google.com/g/2005'>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact' />
<title type='text'>Elizabeth Bennet</title>
<content type='text'>Notes</content>
<gd:email rel='http://schemas.google.com/g/2005#work'
address='liz@gmail.com' />
<gd:email rel='http://schemas.google.com/g/2005#home'
address='liz@example.org' />
<gd:phoneNumber rel='http://schemas.google.com/g/2005#work'
primary='true'>
(206)555-1212
</gd:phoneNumber>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#home'>
(206)555-1213
</gd:phoneNumber>
<gd:im address='liz@gmail.com'
protocol='http://schemas.google.com/g/2005#GOOGLE_TALK'
rel='http://schemas.google.com/g/2005#home' />
<gd:postalAddress rel='http://schemas.google.com/g/2005#work'
primary='true'>
1600 Amphitheatre Pkwy Mountain View
</gd:postalAddress>
</entry>
读取文件并解析:
String file = "C:\\Documents and Settings\\user\\Desktop\\create.xml";
String line = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((line = br.readLine()) !=null) {
sb.append(line);
}
System.out.println("sb.toString() = " + sb.toString());
def xmlf = new XmlSlurper().parseText(sb.toString())
.declareNamespace(gContact:'http://schemas.google.com/contact/2008',
gd:'http://schemas.google.com/g/2005')
println xmlf.title
【问题讨论】:
-
“我将 atom xml 保存到使用 ansi 编码的文件中”到底是什么意思?你到底是如何解析 XML 的?一些代码会有所帮助...
-
我的意思是我用记事本++创建了一个编码类型为ansi的文件。我做了一个复制粘贴。
-
您还有失败的 XML 示例吗?
-
@erimerturk:这意味着您已经应用了多个解码/编码通道 - 我并不奇怪这是错误的。在可能的情况下,尝试不进入编码业务。有关更多详细信息,请参阅我的答案 - 但尚不清楚为什么您甚至 得到 一个文件。我假设实际上 XML 来自网络流 - 所以让 XmlSlurper 将该流解析为 作为 InputStream。
标签: xml groovy atom-feed xmlslurper