Tell me, please, I need to unzip a simple XML of the form:

<?xml version="1.0" encoding="UTF-8"?> <result> <status code="200" /> <building number="434" part="0" url="">Gu</building> </result> 

Tell me how to make it easier? Does MB have any simple class for parisng? Somewhere I saw an analogue php's simplexml, but now I can not find

    4 answers 4

    I would write the simplest parser based on SAX like this (it is written on my knees, so please do not throw tomatoes!)

     factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); xpp = factory.newPullParser(); StringReader sw=new StringReader(s); //s содержит ваш XML xpp.setInput(sw); //подаем на вход парсера int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) //начальный тег { inBuilding=false; if(xpp.getName().compareTo("status")==0) code = xpp.getAttributeValue(null, "code"); //читаем атрибут code else if(xpp.getName().compareTo("building")==0) { number = xpp.getAttributeValue(null, "number"); part = xpp.getAttributeValue(null, "part"); url = xpp.getAttributeValue(null, "url"); inBuilding=true; } } else if(eventType==XmlPullParser.TEXT) { if(inBuilding) //если мы внутри тега building buildingValue=xpp.getText(); }; } 

    Naturally, the values ​​of attributes, fields, and so on. after reading it is necessary to add somewhere. Well, you're already there yourself further :)

      In Java, a lot of tools to work with XML.

      An example of deserialization using Simple

       Serializer s = new Persister(); Example e =, new File("example.xml")); 


        XML Pull Parser functionality that defines parsing functionality ...

          Read here:

          Another option:

           //вспомогательный метод - получает содержимое тэга String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } void test() { File xmlFile = new File(PathToFile); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); doc.getDocumentElement().getNodeName(); //имя корневого тэга NodeList nList = doc.getElementsByTagName("building"); //получаем все теги building for (int nodeIndex = 0; nodeIndex < nList.getLength(); temp++) { //пробегаем тэги Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; getTagValue("building", eElement); //получить содержимое текущего тэга eElement.getAttribute("number"); //получить значение аттрибута } } }