美文网首页
使用JAXB解析XML文件

使用JAXB解析XML文件

作者: 好学人 | 来源:发表于2020-04-23 20:30 被阅读0次

业务背景

最近公司要给APP增加几种语言,因此需要将项目内的string.xml文件拿给翻译去做多语种,但xml这种格式对小白来说,体验不够友好,而且要翻译的内容多达3000多行,一旦翻译错位或某行丢失,将会给后续工作带来极大的麻烦。于是就想到开发一款软件实现傻瓜式操作。

要翻译的文件(string.xml)格式如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="apply">应用</string>
    <string name="confirm">确定</string>
    ......
</resources>

思路分析

软件的设计思路也非常简单,只需要提取出string.xml中每条对应的内容,做完翻译后再更新回去即可。

GUI可以使用JavaFx实现,XML解析可以使用Java自带的JAXB。

代码实现

这里只贴上核心代码,以供日后参考。

1. 建立string.xml对应的JavaBean

@XmlRootElement(name = "resource")
public class ResBean {

    @XmlElement(name = "string")
    public List<ItemBean> list;
    
}
public class ItemBean {

    @XmlAttribute
    public String name;

    @XmlValue
    public String value;
    
}

2. 将string.xml映射为JavaBean

File file = new File("strings.xml");
ResBean resBean = JAXB.unmarshal(file, ResBean.class);

3. 更新实体类后保存到strings.xml

File file = new File("strings.xml");
JAXB.marshal(resBean, file);

相关文章

网友评论

      本文标题:使用JAXB解析XML文件

      本文链接:https://www.haomeiwen.com/subject/skrzihtx.html