[置顶]pull解析器: 反序列化与序列化

本文介绍如何使用 XML Pull 解析器进行序列化与反序列化操作,包括从 XML 文件中读取数据到 Java 对象及将 Java 对象数据写入 XML 文件的过程。
 

  pull解析器:反序列化  读取xml文件来获取一个对象的数据

 

 1 import java.io.FileInputStream;
 2 import java.io.IOException;
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.xmlpull.v1.XmlPullParser;
 7 import org.xmlpull.v1.XmlPullParserException;
 8 import org.xmlpull.v1.XmlPullParserFactory;
 9 
10 public class ReadXmlTest {
11 
12     /**
13      *   pull解析器:反序列化     读取xml文件来获取一个对象的数据
14      * @param args
15      * @throws XmlPullParserException 
16      * @throws IOException 
17      */
18     public static void main(String[] args) throws XmlPullParserException, IOException {
19 
20         //1.导包
21         //2.获取解析器工厂
22         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
23         //3.根据工厂获取解析器对象
24         XmlPullParser parser = factory.newPullParser();
25         //4.设置输入流
26         parser.setInput(new FileInputStream("src/student.xml"),"utf-8");
27         //5.解析
28         List<Student> list = null;
29         Student stu = null;
30         //获取对应时间的类型
31         int type = parser.getEventType(); 
32         while(type != XmlPullParser.END_DOCUMENT){
33             //获取标签名称
34             String tagname = parser.getName();
35             switch(type){
36             case XmlPullParser.START_TAG:
37                 //判断标签名称
38                 if("students".equals(tagname)){
39                     //创建集合
40                     list = new ArrayList<Student>();
41                 }else if("student".equals(tagname)){
42                     //创建对象
43                     stu = new Student();
44                     //获取ID属性值
45                     String id = parser.getAttributeValue(0);
46                     //赋值
47                     stu.setId(id);
48                 }else if("name".equals(tagname)){
49                     //获取标签体的文本
50                     String name = parser.nextText();
51                     //赋值
52                     stu.setName(name);
53                 }else if("age".equals(tagname)){
54                     //获取标签体的文本
55                     String age = parser.nextText();
56                     //赋值
57                     stu.setAge(Integer.parseInt(age));
58             }
59                 break;
60             case XmlPullParser.END_TAG:
61                 if("student".equals(tagname)){
62                     //将对象添加到集合中
63                     list.add(stu);
64                     stu = null;
65                 }
66                 break;
67             default:
68                 break;
69             }
70         //向下走一步
71         parser.next();
72         //重新赋值
73         type = parser.getEventType();
74         }
75         //6.输出
76         System.out.println(list);
77     }
78 }

 

------------------------------------------------------------------------------------------------

 

  pull解析器:序列化    将一个对象的数据  写入到xml文件中

 

 1 import java.io.FileOutputStream;
 2 import java.io.IOException;
 3 
 4 import org.xmlpull.v1.XmlPullParserException;
 5 import org.xmlpull.v1.XmlPullParserFactory;
 6 import org.xmlpull.v1.XmlSerializer;
 7 
 8 public class WriteXmlTest {
 9 
10     /**pull解析器:序列化   将一个对象的数据  写入到xml文件中
11      * @param args
12      * @throws XmlPullParserException 
13      * @throws IOException 
14      */
15     public static void main(String[] args) throws XmlPullParserException, IOException {
16 
17         Student stu = new Student("s_001", "小飞飞", 23);
18         //1.导包
19         //2.获取解析器工厂
20         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
21         //3.根据工厂获取解析器对象
22         XmlSerializer serializer = factory.newSerializer();
23         //4.设置输出流
24         serializer.setOutput(new FileOutputStream("src/sss.xml"),"utf-8");
25         //5.写入
26         //5.1写文档声明  参数1:encoding属性值,参数2:standalone属性值
27         serializer.startDocument("utf-8", true);
28         //5.2写入开始跟标签
29         serializer.startTag(null, "students");
30         for(int i=0; i <5; i++){
31             //5.3写入student标签
32             serializer.startTag(null, "student");
33             
34             serializer.attribute(null, "id", stu.getId());
35             
36             serializer.startTag(null, "name");
37             serializer.text(stu.getName());
38             serializer.endTag(null, "name");
39             
40             serializer.startTag(null, "age");
41             serializer.text(String.valueOf(stu.getAge()));
42             serializer.endTag(null, "age");
43             
44             serializer.endTag(null, "student");
45         }
46         //5.4写入结束标签
47         serializer.endTag(null, "students");
48         //5.5写入结束文档
49         serializer.endDocument();
50         //反应结果
51         System.out.println("写入完成,请去查看!");
52     }
53 }

 

  Student类

 

 1 public class Student {
 2 
 3     private String id;
 4     private String name;
 5     private int age;
 6     
 7     public Student() {
 8         super();
 9     }
10     public Student(String id, String name, int age) {
11         super();
12         this.id = id;
13         this.name = name;
14         this.age = age;
15     }
16     /**
17      * @return the id
18      */
19     public String getId() {
20         return id;
21     }
22     /**
23      * @param id the id to set
24      */
25     public void setId(String id) {
26         this.id = id;
27     }
28     /**
29      * @return the name
30      */
31     public String getName() {
32         return name;
33     }
34     /**
35      * @param name the name to set
36      */
37     public void setName(String name) {
38         this.name = name;
39     }
40     /**
41      * @return the age
42      */
43     public int getAge() {
44         return age;
45     }
46     /**
47      * @param age the age to set
48      */
49     public void setAge(int age) {
50         this.age = age;
51     }
52     /* (non-Javadoc)
53      * @see java.lang.Object#toString()
54      */
55     @Override
56     public String toString() {
57         return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
58     }
59 
60 }

 

  student.xml

 1 <?xml version='1.0' encoding='utf-8' ?>
 2 
 3 <students>
 4     <student id='s001'>
 5         <name>zhangsan</name>
 6         <age>23</age>
 7     </student>
 8         
 9     <student id="s002">
10         <name>lisi</name>
11         <age>24</age>
12     </student>
13 
14     <student id="s003">
15         <name>王五</name>
16         <age>25</age>
17     </student>
18     
19 </students>

 

导入的包名称(pull解析器jar包):

  kxml2-2.3.0.jar

  xmlpull_1_1_3_4c.jar

 

<!-- pages/goods/list.vue --> <template> <view class="goods-list-container"> <!-- 顶部标题栏 --> <view class="header"> <uni-icons type="back" size="24" color="#fff" class="back-icon" @click="goBack" /> <view class="title-container"> <text class="title">货物信息列表</text> </view> </view> <!-- 货物列表 --> <scroll-view scroll-y class="goods-list" :refresher-enabled="false" @scrolltolower="onReachBottom" > <!-- 上拉刷新提示 --> <view class="pull-up-hint" v-if="isLoading"> <uni-icons type="spinner-cycle" size="24" color="#5e8fff" class="loading-icon" /> <text>加载中...</text> </view> <!-- 货物卡片 --> <view v-for="(item, index) in goodsList" :key="item.id" class="goods-card" @click="getOrderInfo(item.name)" > <view class="card-header"> <text class="goods-name">{{ item.name }}</text> <text class="goods-code">#{{ item.code }}</text> </view> <view class="card-content"> <view class="info-row"> <text class="info-label">分类:</text> <text class="info-value">{{ item.category }} / {{ item.subCategory }}</text> </view> <view class="info-row"> <text class="info-label">库存:</text> <view class="stock-info"> <text class="info-value">{{ item.quantity }} {{ item.unit }}</text> <text class="safety-stock">安全库存: {{ item.safetyStock }}{{ item.unit }}</text> </view> </view> <view class="info-row"> <text class="info-label">状态:</text> <text :class="[ 'status-tag', item.status === 'normal' ? 'status-normal' : item.status === 'warning' ? 'status-warning' : 'status-danger' ]"> {{ item.status === 'normal' ? '库存正常' : item.status === 'warning' ? '库存预警' : '库存不足' }} </text> </view> <view class="info-row"> <text class="info-label">位置:</text> <text class="info-value">{{ item.warehouse }} - {{ item.storageLocation }}</text> </view> </view> <view class="card-footer"> <text class="in-date">入库时间:{{ item.inDate }}</text> </view> </view> <!-- 空状态提示 --> <view v-if="goodsList.length === 0" class="empty-state"> <uni-icons type="box" size="50" color="#ccc"></uni-icons> <text class="empty-text">暂无货物信息</text> </view> <!-- 加载完成提示(不显示空白) --> <view v-if="loadComplete" class="no-more-hint"> <text>没有更多货物信息了</text> </view> </scroll-view> </view> </template> <script> export default { data() { return { isLoading: false, // 加载状态 loadComplete: false, // 加载完成标志 pageSize: 5, // 每页加载数量 currentPage: 1, // 当前页码 totalPages: 3, // 总页数 goodsList: [], // 货物列表数据 baseData: [ // 基础货物数据 { id: '1', code: 'G2023001', name: '金属螺丝', category: '原材料', subCategory: '金属件', unit: '件', quantity: 1200, safetyStock: 500, status: 'normal', warehouse: '主仓库A区', storageLocation: 'A区-3排-2层', inDate: '2023-05-10' }, { id: '2', code: 'G2023002', name: '电路板', category: '电子产品', subCategory: '电子元件', unit: '块', quantity: 85, safetyStock: 100, status: 'warning', warehouse: '主仓库B区', storageLocation: 'B区-1排-5层', inDate: '2023-06-15' }, { id: '3', code: 'G2023003', name: '打印纸', category: '办公用品', subCategory: '纸张', unit: '包', quantity: 20, safetyStock: 30, status: 'warning', warehouse: '备用仓库', storageLocation: 'C区-2排-1层', inDate: '2023-07-20' }, { id: '4', code: 'G2023004', name: '塑料外壳', category: '原材料', subCategory: '塑料件', unit: '个', quantity: 850, safetyStock: 400, status: 'normal', warehouse: '主仓库A区', storageLocation: 'A区-4排-3层', inDate: '2023-04-05' }, { id: '5', code: 'G2023005', name: 'LED显示屏', category: '电子产品', subCategory: '显示设备', unit: '台', quantity: 12, safetyStock: 15, status: 'warning', warehouse: '备用仓库', storageLocation: 'C区-3排-2层', inDate: '2023-08-12' } ] } }, onLoad() { // 初始化加载数据 this.loadGoodsData(); }, methods: { //获取货物信息并跳转到货物信息详细页面 getOrderInfo(item){ console.log(item) uni.navigateTo({ url: '/pages/tabbar/storageManagement/OrderInfo' }) }, // 加载货物数据 loadGoodsData() { this.isLoading = true; // 模拟API请求延迟 setTimeout(() => { // 生成模拟数据 const mockData = this.generateMockData(); // 如果是第一页,直接赋值 if (this.currentPage === 1) { this.goodsList = mockData; } else { // 后续页面追加数据 this.goodsList = [...this.goodsList, ...mockData]; } // 检查是否加载完成 if (this.currentPage >= this.totalPages) { this.loadComplete = true; } this.isLoading = false; }, 800); }, // 生成模拟数据 generateMockData() { const newData = []; const baseCount = this.baseData.length; for (let i = 0; i < this.pageSize; i++) { const baseIndex = (i + (this.currentPage - 1) * this.pageSize) % baseCount; const baseItem = this.baseData[baseIndex]; const newItem = { ...baseItem, id: `${baseItem.id}-${this.currentPage}-${i}`, code: `G${2023 + this.currentPage}${100 + i}`, quantity: Math.max(0, baseItem.quantity - (this.currentPage - 1) * 50), inDate: this.generateRandomDate() }; // 根据库存数量设置状态 if (newItem.quantity > newItem.safetyStock * 1.2) { newItem.status = 'normal'; } else if (newItem.quantity > newItem.safetyStock * 0.5) { newItem.status = 'warning'; } else { newItem.status = 'danger'; } newData.push(newItem); } return newData; }, // 生成随机日期 generateRandomDate() { const start = new Date(2023, 0, 1); const end = new Date(); const randomDate = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); return `${randomDate.getFullYear()}-${(randomDate.getMonth() + 1).toString().padStart(2, '0')}-${randomDate.getDate().toString().padStart(2, '0')}`; }, // 上拉触底事件 onReachBottom() { if (this.isLoading || this.loadComplete) return; this.currentPage++; this.loadGoodsData(); }, // 返回 goBack() { uni.navigateTo({ url: '/pages/tabbar/storageManagement/selectOrder' }); } } } </script> <style scoped> /* 确保所有元素使用border-box模型 */ * { box-sizing: border-box; margin: 0; padding: 0; } .goods-list-container { display: flex; flex-direction: column; height: 100vh; background-color: #f5f7fa; } /* 顶部标题栏 */ .header { background: linear-gradient(135deg, #5e8fff, #6b7de9); padding: 15px 20px; display: flex; align-items: center; color: #fff; box-shadow: 0 2px 10px rgba(94, 143, 255, 0.3); position: relative; z-index: 10; } .back-icon { padding: 5px; z-index: 1; } .title-container { position: absolute; left: 50%; transform: translateX(-50%); width: 100%; text-align: center; } .title { font-size: 18px; font-weight: bold; } /* 货物列表 */ .goods-list { flex: 1; padding: 15px; height: 100%; background-color: #f5f7fa; } /* 上拉刷新提示 */ .pull-up-hint { display: flex; justify-content: center; align-items: center; padding: 10px; color: #5e8fff; font-size: 14px; background-color: #f5f7fa; } .loading-icon { animation: spin 1s linear infinite; margin-right: 8px; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* 货物卡片 */ .goods-card { background: #fff; border-radius: 12px; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08); margin-bottom: 15px; padding: 20px; position: relative; overflow: hidden; transition: all 0.3s ease; } .goods-card:active { background-color: #f8f9ff; } .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #eee; } .goods-name { font-size: 17px; font-weight: bold; color: #333; } .goods-code { font-size: 13px; color: #999; background: #f0f2f5; padding: 3px 8px; border-radius: 4px; } .card-content { margin-bottom: 15px; } .info-row { display: flex; margin-bottom: 12px; font-size: 14px; align-items: flex-start; } .info-label { width: 70px; color: #666; flex-shrink: 0; } .info-value { flex: 1; color: #333; line-height: 1.5; } .stock-info { display: flex; flex-direction: column; } .safety-stock { margin-top: 5px; color: #888; font-size: 13px; } .status-tag { padding: 4px 12px; border-radius: 15px; font-size: 13px; font-weight: 500; display: inline-block; } .status-normal { background: #e8f5e9; color: #4caf50; } .status-warning { background: #fff8e1; color: #ff9800; } .status-danger { background: #ffebee; color: #f44336; } .card-footer { padding-top: 12px; border-top: 1px solid #f5f5f5; color: #888; font-size: 13px; display: flex; justify-content: flex-start; } /* 加载完成提示(不占用多余空间) */ .no-more-hint { text-align: center; padding: 12px 0; color: #aaa; font-size: 13px; background-color: #f5f7fa; } /* 空状态提示 */ .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 70vh; color: #999; text-align: center; } .empty-text { margin: 15px 0; font-size: 15px; } </style> 用uniapp生成货物的详细信息页面,并将所有信息以点号来间隔组成一串字符串,并将这字符串转换成条形码,将条形码放置所有信息的前面
最新发布
11-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jusenr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值