[英]Parse xml with special characters in GROOVY
I want reads an xml and then I have to do insert on database.我想读取一个 xml 然后我必须在数据库上插入。 My problem is when a value contains special characters.
我的问题是当值包含特殊字符时。
def xmlResponse = """<?xml version="1.0" encoding="UTF-8"?>
<nm>
<item>
<Row>
<cod>1</cod>
<desc>RPAS <Management></desc>
</Row>
<Row>
<cod>110</cod>
<desc>FIGHTER3 & SIMULATION</desc>
</Row>
</item>
<nm>"""
My code is:我的代码是:
def parser = new XmlSlurper()
def xmlPars = "${xmlResponse}".replaceAll("&", "&")
xmlPars2 = "${xmlPars}".replaceAll("<Management>", "<"+"<Management"+">")
def xml = parser.parseText("${xmlPars2}")
This works only for the string 'Management' and not for all cases, because if I do the replace of all '<' and '>' than the parser return an error.这仅适用于字符串“Management”而不适用于所有情况,因为如果我替换所有“<”和“>”,解析器将返回错误。
Can you help me to write a code that works always?你能帮我写一个永远有效的代码吗?
I don't want escape these characters (if is possible) because my insert should contain the string as well as.我不想转义这些字符(如果可能的话),因为我的插入内容也应该包含字符串。
it's not a valid xml, and what you are doing - trying to fix the result of incorrect xml formatting.它不是有效的 xml,您在做什么 - 试图修复不正确的 xml 格式的结果。 better to fix place where you are building this xml...
最好修复你正在构建这个 xml 的地方......
however there is an easy way that could work for you:但是,有一种简单的方法可以为您工作:
def xmlResponse = """<?xml version="1.0" encoding="UTF-8"?>
<nm>
<item>
<Row>
<cod>1</cod>
<desc>RPAS <Management></desc>
</Row>
<Row>
<cod>110</cod>
<desc>FIGHTER3 & SIMULATION</desc>
</Row>
</item>
</nm>"""
//let's convert each <desc>...</desc>
// to <desc><![CDATA[...]]></desc>
// then value inside CDATA does not require xml escaping
xmlResponse = xmlResponse.replaceAll('<desc>','<desc><![CDATA[').replaceAll('</desc>',']]></desc>')
def xml = new XmlSlurper().parseText(xmlResponse)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.