简体   繁体   English

在Android Studio上反序列化xml文件

[英]Deserialize xml file on android studio

I wrote an app that uses an xml file I created, and I need to deserialize it to a list. 我编写了一个使用创建的xml文件的应用程序,需要将其反序列化为列表。 Each item in the list has some properties and an inside list. 列表中的每个项目都有一些属性和一个内部列表。 For example: <persons> <person> <FirstName>fn1</FirstName> <LastName>ln1</LastName> <Age>30</Age> <FavoriteColors> <ColorItem> <ColorName>red</ColorName> <IsFavorite>True</IsFavorite> </ColorItem> <ColorItem> <ColorName>blue</ColorName> <IsFavorite>False</IsFavorite> </ColorItem> </FavoriteColors> </person> <person> <FirstName>fn2</FirstName> <LastName>ln2</LastName> <Age>20</Age> <FavoriteColors> <ColorItem> <ColorName>white</ColorName> <IsFavorite>False</IsFavorite> </ColorItem> <ColorItem> <ColorName>black</ColorName> <IsFavorite>False</IsFavorite> </ColorItem> <ColorItem> <ColorName>pink</ColorName> <IsFavorite>True</IsFavorite> </ColorItem> </FavoriteColors> </person> </persons> I know how to do it on c#, but I'm new to java and couldn't find a way to do that. 例如: <persons> <person> <FirstName>fn1</FirstName> <LastName>ln1</LastName> <Age>30</Age> <FavoriteColors> <ColorItem> <ColorName>red</ColorName> <IsFavorite>True</IsFavorite> </ColorItem> <ColorItem> <ColorName>blue</ColorName> <IsFavorite>False</IsFavorite> </ColorItem> </FavoriteColors> </person> <person> <FirstName>fn2</FirstName> <LastName>ln2</LastName> <Age>20</Age> <FavoriteColors> <ColorItem> <ColorName>white</ColorName> <IsFavorite>False</IsFavorite> </ColorItem> <ColorItem> <ColorName>black</ColorName> <IsFavorite>False</IsFavorite> </ColorItem> <ColorItem> <ColorName>pink</ColorName> <IsFavorite>True</IsFavorite> </ColorItem> </FavoriteColors> </person> </persons>我知道如何在c#上进行操作,但是我是java的新手,所以找不到解决方法。 What is the best, shorter and easiest way to do that? 最好,更短和最简单的方法是什么? do I need to build classes for it like in c#? 我需要像在c#中那样为其构建类吗? or are there commands to go threw over the xml elements to build my list? 还是有一些命令可以遍历xml元素来建立我的列表? is json would be better over xml? json比xml更好吗? if so, how do I deserialize json? 如果是这样,我如何反序列化json? Thanks for the helpers! 感谢您的帮手! :) :)

For those who need the solution, this is how I solved it. 对于那些需要解决方案的人,这就是我解决的方法。 I used dom parser. 我使用了dom解析器。

First, I created a class for the favoriteColors with its properties. 首先,我为最喜欢的颜色及其属性创建了一个类。

public class FavoriteColors
{
    private String ColorName;
    private boolean IsFavorite;

    public FavoriteColors(String _colorName, boolean _isFavorite)
    {
        this.ColorName = _colorName;
        this.IsFavorite = _isFavorite;
    }
}

Then, I created a class for the person with its properties. 然后,我为具有该属性的人创建了一个类。

public class Person
{
    private String FirstName;
    private String LastName;
    private String Age;
    private List<FavoriteColors> AllColors = new ArrayList<FavoriteColors>();

    public Person(String _firstName, String _lastName, String _age, List<FavoriteColors> _allColors)
    {
        this.FirstName = _firstName;
        this.LastName = _lastName;
        this.Age = _age;
        for (int i = 0; i < _allColors.size(); i++)
        {
            this.AllColors.add(_allColors.get(i));
        }
    }
}

The parse code: You need to read your xml file to a string (or in any other way you choose) and the final list where all data is collecting to is listOfPersons, which I defined in the code. 解析代码:您需要将xml文件读取为一个字符串(或以您选择的任何其他方式),并且所有数据收集到的最终列表是listOfPersons,我在代码中定义了该列表。

    public static void main(String[] args) 
    {
        String xmlFile = "your xml file"  // read your xml file to string

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xmlFile));
            Document document = builder.parse(is);

            List<Person> listOfPersons = new ArrayList<Person>();
            NodeList nodeList = document.getDocumentElement().getChildNodes();

            for (int i = 0; i < nodeList.getLength(); i++)
            {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element elem = (Element) node;
                    String firstNameText = "";
                    if (elem.getElementsByTagName("FirstName").item(0).getChildNodes().item(0) != null)
                    {
                        firstNameText = elem.getElementsByTagName("FirstName").item(0).getChildNodes().item(0).getNodeValue();
                    }
                    String lastNameText = "";
                    if (elem.getElementsByTagName("LastName").item(0).getChildNodes().item(0) != null)
                    {
                        lastNameText = elem.getElementsByTagName("LastName").item(0).getChildNodes().item(0).getNodeValue();
                    }
                    String ageText = "";
                    if (elem.getElementsByTagName("Age").item(0).getChildNodes().item(0) != null)
                    {
                        ageText = elem.getElementsByTagName("Age").item(0).getChildNodes().item(0).getTextContent();
                    }

                    List<FavoriteColors> listOfColors = new ArrayList<FavoriteColors>();
                    NodeList nl = elem.getElementsByTagName("FavoriteColors").item(0).getChildNodes();

                    for (int j = 0; j < nl.getLength(); j++)
                    {
                        Node n = nl.item(j);

                        if (n.getNodeType() == Node.ELEMENT_NODE)
                        {
                            Element e = (Element) n;
                            String colorName = "";
                            if (e.getElementsByTagName("ColorName").item(0).getChildNodes().item(0) != null)
                            {
                                colorName = e.getElementsByTagName("ColorName").item(0).getChildNodes().item(0).getNodeValue();
                            }
                            boolean isFavorite = false;
                            if (e.getElementsByTagName("IsFavorite").item(0).getChildNodes().item(0).getNodeValue() != null)
                            {
                                isFavorite = Boolean.parseBoolean(e.getElementsByTagName("IsFavorite").item(0).getChildNodes().item(0).getNodeValue());
                            }

                            listOfColors.add(new FavoriteColors(colorName, isFavorite));
                        }
                    }

                    listOfPersons.add(new Person(firstNameText, lastNameText, ageText, listOfColors));
                }
            }
        } 
        catch (ParserConfigurationException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Hope it will help others. 希望它能帮助别人。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM