fix XmlUtil

This commit is contained in:
Looly 2021-06-20 00:46:57 +08:00
parent 2465c024b7
commit e8ecadd9a3
4 changed files with 31 additions and 1 deletions

View File

@ -20,6 +20,7 @@
* 【poi 】 修复使用BigWriter写出ExcelWriter修改单元格值失败的问题issue#I3VSDO@Gitee
* 【jwt 】 修复Hmac算法下生成签名是hex的问题issue#I3W6IP@Gitee
* 【core 】 修复TreeUtil.build中deep失效问题issue#1661@Github
* 【json 】 修复XmlUtil.xmlToBean判断问题issue#1663@Github
-------------------------------------------------------------------------------------------------------------

View File

@ -1024,7 +1024,11 @@ public class XmlUtil {
public static <T> T xmlToBean(Node node, Class<T> bean) {
final Map<String, Object> map = xmlToMap(node);
if (null != map && map.size() == 1) {
return BeanUtil.toBean(map.get(bean.getSimpleName()), bean);
final String simpleName = bean.getSimpleName();
if(map.containsKey(simpleName)){
// 只有key和bean的名称匹配时才做单一对象转换
return BeanUtil.toBean(map.get(simpleName), bean);
}
}
return BeanUtil.toBean(map, bean);
}

View File

@ -1,5 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Console;
@ -214,6 +215,29 @@ public class XmlUtilTest {
Assert.assertEquals(testBean.getBankCode(), testBean2.getBankCode());
}
@Test
public void xmlToBeanTest2(){
//issue#1663@Github
String xmlStr = "<?xml version=\"1.0\" encoding=\"gbk\" ?><response><code>02</code></response>";
Document doc = XmlUtil.parseXml(xmlStr);
// 标准方式
Map<String, Object> map = XmlUtil.xmlToMap(doc.getFirstChild());
SmsRes res = new SmsRes();
BeanUtil.fillBeanWithMap(map, res, true);
// toBean方式
SmsRes res1 = XmlUtil.xmlToBean(doc.getFirstChild(), SmsRes.class);
Assert.assertEquals(res.toString(), res1.toString());
}
@Data
static class SmsRes {
private String code;
}
@Test
public void cleanCommentTest() {
final String xmlContent = "<info><title>hutool</title><!-- 这是注释 --><lang>java</lang></info>";

View File

@ -13,4 +13,5 @@ public class XMLTest {
final String s = JSONUtil.toXmlStr(put);
Assert.assertEquals("<aaa>你好</aaa><键2>test</键2>", s);
}
}