Разбор Android xml с тем же именем элемента в Android? - PullRequest
2 голосов
/ 17 января 2012

я хочу разобрать xml файл у меня есть xml вот так

<parent>
  <Title>1</Title>
  <child>"Some data1"</child>
  <child>"Some data2"</child>
  <child>"Some data3"</child>
</parent>
<parent>
  <Title>2</Title>
  <child>"Some data1"</child>
  <child>"Some data2"</child>
  <child>"Some data3"</child>
 </parent>

любая идея разбирать xml вот так (UP сторона)

Edit:

если такая структура

 <parent>
  <Title>2</Title>
  <child>"Some data1"</child>
 </parent>

я использую

  NodeList nodes1 = doc.getElementsByTagName("parent");                  

        for (int i = 0; i < nodes1.getLength(); i++) {

            Objectclass ciro = new   Objectclass ();
            Element e = (Element)nodes1.item(i);
            ciro.Title = functionsClass.getValue(e, "Title");
            ciro.child= functionsClass.getValue(e, "child");

            ArrayListClass.ItemList.add(ciro);

            }

здесь я храню данные в классе объектов, затем добавляю объект в список массивов, затем использую данные там, где мне нужно.

но проблема с тем же именем ребенка в родительском как я могу получить эти значения ..

 <parent>
  <Title>1</Title>
 <child>"Some data1"</child>
 <child>"Some data2"</child>
 <child>"Some data3"</child>
</parent>
<parent>
 <Title>2</Title>
 <child>"Some data1"</child>
 <child>"Some data2"</child>
 <child>"Some data3"</child>
</parent>

любой учебник для этого ..

Ответы [ 4 ]

1 голос
/ 17 января 2012

ваш ciro.child должен быть массивом списков строк.

использовать следующие

node1 = doc.getElementsByTagName ("parent");

    for (int i = 0; i < nodes1.getLength(); i++) {

        Objectclass ciro = new   Objectclass ();
        Element e = (Element)nodes1.item(i);

        NodeList list=e.items();

        for(int j=0;j<list.getLength();j++)
        {
            Node item=list.getNode(j);
            if(item.getNodeName().equals("title"))
                ciro.title=item.getNodeValue();
            else if(item.getNodeName().equals("child")
                ciro.childs.add(item.getNodeValue());

        }



        }
0 голосов
/ 17 января 2012

используйте этот код, возможно, это поможет ..

   nodes1 = doc.getElementsByTagName("parent");                  

        for (int i = 0; i < nodes1.getLength(); i++) {

            ObjectClass cgro = new ObjectClass();
            Element e = (Element)nodes1.item(i);
            cgro.Title = XMLfunctions.getValue(e, "Title");


            nodes1a = doc.getElementsByTagName("child");

            for(int j = 0; j < nodes1a.getLength(); j++ ){

                ObjectClass1 cgro1 = new ObjectClass1();

                 Element e2= (Element) nodes1a.item(j);
                 cgro1.child= XMLfunctions.getCharacterDataFromElement(e2);
                 ArrayListClass.ItemList1.add(cgro1);
            }


            ArrayListClass.ItemList2.add(cgro);

            }

и класс использования для этого

    public class XMLfunctions {

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}

/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 public static String getXML(){  
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://p-xr.com/xml");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        }

        return line;

}

public static int numResults(Document doc){     
    Node results = doc.getDocumentElement();
    int res = -1;

    try{
        res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
    }catch(Exception e ){
        res = -1;
    }

    return res;
}

public static String getValue(Element item, String str) {       
    NodeList n = item.getElementsByTagName(str);        
    return XMLfunctions.getElementValue(n.item(0));
}

public static String getCharacterDataFromElement(Element e) {
      Node child = e.getFirstChild();
      if (child instanceof CharacterData) {
         CharacterData cd = (CharacterData) child;
         return cd.getData();
      }
      return "?";
    }

   }

может ли это помочь вам ...

0 голосов
/ 17 января 2012

считать = 0;и наступает момент, когда элемент подходит к концу, просто поместите символы в массив строк и увеличьте счетчик, а затем после элемента end, если тот же элемент заявляет, затем сделайте charte set равным нулю и снова получите символы, а в конце элемента вы поместите его в массиви так далее .....

0 голосов
/ 17 января 2012

В чем проблема?Я не могу понятьdom, sax, pull ... с любым парсером ваши данные могут быть проанализированы.просто создайте модель, создайте ArrayList, итерируйте теги и сохраните данные в вашей модели.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...