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

@@ -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>";