Let's Go!
01_groovy: xml写入和解析
上一篇 /
下一篇 2011-05-18 23:42:02
/ 个人分类:groovy
content ="""<?xml version="1.0" ?>
<customers>
<corporate>
<customer name="Bill Gates" company="Microsoft" />
<customer name="Steve Jobs" company="Apple" />
<customer name="Jonathan Schwartz" company="Sun" />
</corporate>
<consumer>
<customer name="John Doe" />
<customer name="Jane Doe" />
</consumer>
</customers>"""
customersFile = new File("D:\\java\\groovycode\\cs.xml")
pw = new PrintWriter(customersFile)
pw.print(content);
pw.flush() ;
pw.close() ;
customersFile.eachLine { println it}
println "==========================================================="
//def customers = new XmlSlurper().parse(new File("D:\\java\\groovycode\\cs.xml"))
def customers = new XmlSlurper().parse(customersFile)
for (customer in customers.corporate.customer)
{
println "${customer.@name} works for${customer.@company}"
}
遇到的问题和解决方法:
1. The processing instruction target matching "[xX][mM][lL]" is not allowed.
Exception:org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
这个异常解释为:xml文件不能被解析,一般出现这样的问题在于xml格式上,并且问题多出现在xml文件的头部。我就是出现了这个问题。昨天还可以正常运行的,今天来了就运行不了了,很奇怪,查看了下错误信息,找到了原因。这是因为我的xml文件头部有两行空行,第三行才开始写
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
的。总结:<?xml version="1.0" encoding="UTF-8"?>前面不要有任何其他字符,如空格、回车、换行这些否则就会出现上面的异常。
http://hi.baidu.com/mingfang0219/blog/item/3e84764226331f1873f05df3.html
成功解决问题[Fatal Error] test.xml:1:7: The processing instruction target matching "[xX][mM][lL]" is not allowed. 收藏
对于错误:
[Fatal Error] test.xml:1:7: The processing instruction target matching "[xX][mM][lL]" is not allowed. org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed. at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:264) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:292) at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:172) at TestXML.XmlDemo(TestXML.java:98) at TestXML.main(TestXML.java:129)
查询了不少资料,在google上查了不少资料,终于把问题给解决了。
这个问题主要是因为xml文件不能解析,一般出现这样的问题是在与xml格式上的问题,并且问题多出现在xml文件的头部。
于是我将xml文件用记事本打开仔细检查了下,果然是xml文件的头部多出了一个问题,将空格去掉保存好了,解析xml文件并读取其中数据就成功了!
ps.这个xml文件是我自己为了检测程序,自己写的,所以有疏漏,一般机器生成的xml文件应该不存在这样的问题,另外,我在网上查找资料的过程中,看见说eclipse中有个选项可以检查xml文件的有效性,但是我没有找到。。。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zhaopeipei1985/archive/2008/07/10/2633853.aspx
收藏
举报
TAG: