概述
Java解析XML(4种方法)
public static void main(String[] args) throws Exception {
//1.创建Reader对象
String s="<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <MtMessageRes> <resDetail> <phoneNumber>15001710000</phoneNumber> <stat>r:000</stat> <statDes>提交成功</statDes> </resDetail> <resDetail> <phoneNumber>15001710008</phoneNumber> <stat>r:000</stat> <statDes>提交成功</statDes> </resDetail> <resDetail> <phoneNumber>15001710009</phoneNumber> <stat>r:000</stat> <statDes>提交成功</statDes> </resDetail> <smsId>4acadda1-5806-4492-9a82-b7ab3f1c8ec0</smsId> <subStat>r:000</subStat> <subStatDes>处理成功</subStatDes> </MtMessageRes>";
SAXReader reader = new SAXReader();
//2.加载xml
Document document = reader.read(new ByteArrayInputStream(s
.getBytes("UTF-8")));
Element rootElement = document.getRootElement();
Iterator iterator = rootElement.elementIterator();
List<Map<String,String>> list=new ArrayList<>();
while (iterator.hasNext()){
Element stu = (Element) iterator.next();
List<Attribute> attributes = stu.attributes();
System.out.println("======获取属性值======");
for (Attribute attribute : attributes) {
System.out.println(attribute.getValue());
}
Iterator iterator1 = stu.elementIterator();
while (iterator1.hasNext()){
Element stuChild = (Element) iterator1.next();
Map<String,String> map=new HashMap();
map.put(stuChild.getName(),stuChild.getStringValue());
list.add(map);
}
}
System.out.println(list);
}
pom文件
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.7.1</version>
</dependency>
实体类
package cn.chaohi.payment.module.pay.controller;
import lombok.Data;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* @author Mr.sunql
* @description
* @date Created in15:19 2021/2/4 0004
*/
@Root(
name = "user",
strict = false
)
@Data
public class User {
@Element(
name = "appid"
)
private String id;
@Element(
name = "appname"
)
private String name;
@Element(
name = "sex"
)
private String sex;
}
public static void main(String[] args) {
User user=new User();
user.setId("111");
user.setName("张三");
user.setSex("女");
String user1=
XmlUtil.toString(user);
System.out.println(user1);
}
<user>
<appid>111</appid>
<appname>张三</appname>
<sex>女</sex>
</user>
使用RestTemplate发送xml数据
RestTemplate restTemplate=new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
StringBuffer xmlString = new StringBuffer();
HttpEntity<String> formEntity = new HttpEntity(xmlString.toString(), headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, formEntity, String.class);
最后
以上就是合适航空为你收集整理的微信支付中:Bean转xml,使用RestTemplate发送xml的全部内容,希望文章能够帮你解决微信支付中:Bean转xml,使用RestTemplate发送xml所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复