【问题标题】:Android parsing all tags using Dom parserAndroid使用Dom解析器解析所有标签
【发布时间】:2013-02-05 07:02:38
【问题描述】:

我正在尝试使用 Dom 解析器解析以下 xml 文件。但我得到了前三个标签 (日期、早餐、午餐)。如何获取所有日期、早餐和午餐标签。

-<Content>
  <Date>2/4/2013</Date>
  <Breakfast>WG Biscuit, Grits, sausage patty, fruit, juice, milk</Breakfast>
  <Lunch>Chicken tenders with sauce, WG affle stick and syrup, carrots-MC, romaine garden salad, fruit, juice, milk</Lunch>
  <Date>2/5/2013</Date>
  <Breakfast>grilleed cheese sandich, grits, fruit, juice, milk</Breakfast>
  <Lunch>meat sauce w/WG pasta, green beans, caesar salad, WW garlic toast, fruit, juice, milk</Lunch>
  <Date>2/6/2013</Date>
  <Breakfast>WG biscuit with chicken patty, fruit, juice, milk</Breakfast>
  <Lunch>WG pizza, spinach salad, WKcorn, fruit, juice, milk</Lunch>
  <Date>2/7/2013</Date>
  <Breakfast>WG french toast sticks (4), sausage links, fruit, juice, milk</Breakfast>
  <Lunch>salisbury steak, black eyed peas, creamed potatoes with gravy, greens-MC, spring mixed salad, WW cornbread, fruit, juice, milk</Lunch>
  <Date>2/8/2013</Date>
  <Breakfast>WG breakfast bagel, yogurt, fruit, juice, milk</Breakfast>
  <Lunch>BBQ rib portion on WG bun, sweet potato fries or yams, romaine garden salad, fruit, juice, milk</Lunch>
  <Date>2/11/2013</Date>
  <Breakfast>Mardi Gras Holiday - No School</Breakfast>
  <Lunch/>
</Content> 

我正在使用以下代码:

StringBuilder sb=new StringBuilder(arg0[0]);
             String findlink=sb.toString();
             try{
                    HttpClient client=new DefaultHttpClient();
                    HttpGet request=new HttpGet();
                    request.setURI(new URI(findlink)) ;

                    HttpResponse response=client.execute(request);
                    //et.setText("its working"); 
                 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

                 DocumentBuilder Builder=factory.newDocumentBuilder();
                 dom=Builder.parse(response.getEntity().getContent());
                 dom.getDocumentElement().normalize();
                  nList5=dom.getElementsByTagName("Content");
                    for(int temp=0;temp<nList5.getLength();temp++)
                    {
                         Node nNode=nList5.item(temp);
                         if(nNode.getNodeType()==Node.ELEMENT_NODE)
                         {
                                    Element eElement=(Element)nNode;
                                    String  base1 =getTagValue("Date",eElement);
                                    Date.add(base1);
                                    String  base2 =getTagValue("Breakfast",eElement);
                                    Breakfast.add(base2);
                                    String  base3 =getTagValue("Lunch",eElement);
                                    Lunch.add(base3);


                          }
                    }

如何解析 content 下的所有标签。帮我做这件事。

【问题讨论】:

  • 我在这个 XML 中发现了一个问题。这三个标签是混合在一起的,它们需要被包裹在一个分隔标签中。您不应该仅仅依赖于对相关标签进行分组的顺序。
  • 第一次学习 wat 你需要做和.. 自己做 :) tutorials.jenkov.com/java-xml/dom.html

标签: android domparser


【解决方案1】:

首先确保您的 XML 数据已格式化,我的意思是它不应遗漏任何标签关闭和大括号 &lt;&gt; 使用任何在线 XML formator 来验证您的 XML。在此之后尝试以下代码。

XML解析器函数

/**
 * Getting XML DOM element
 * 
 * @param XML
 *            string
 * */
public Document getDomElement(String xml) {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setCoalescing(true);
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

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

    } catch (ParserConfigurationException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (SAXException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    }

    return doc;

}

获取节点值。

/**
 * Getting node value
 * 
 * @param Element
 *            node
 * @param key
 *            string
 * */
public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

}

像这样调用上面的函数

            Document doc = parser.getDomElement(yourXMLString);
            NodeList nl = doc.getElementsByTagName("Content");

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

                Element e = (Element) nl.item(i);

                // Get your Data Here

                                String  base1 =getTagValue("Date",eElement);
                                Date.add(base1);
                                String  base2 =getTagValue("Breakfast",eElement);
                                Breakfast.add(base2);
                                String  base3 =getTagValue("Lunch",eElement);
                                Lunch.add(base3);

        }

像这样更改你的 XML

<Contents>
<content>
<Date>2/4/2013
</Date>
<Breakfast>WG Biscuit, Grits, sausage patty, fruit, juice, milk
</Breakfast>
<Lunch>Chicken tenders with sauce, WG affle stick and syrup, carrots-MC, romaine garden salad, fruit, juice, milk
</Lunch>
</content>
<content>
<Date>2/5/2013
</Date>
<Breakfast>grilleed cheese sandich, grits, fruit, juice, milk
</Breakfast>
<Lunch>meat sauce w/WG pasta, green beans, caesar salad, WW garlic toast, fruit, juice, milk
</Lunch>
</content>
<content>
<Date>2/6/2013
</Date>
<Breakfast>WG biscuit with chicken patty, fruit, juice, milk
</Breakfast>
<Lunch>WG pizza, spinach salad, WKcorn, fruit, juice, milk
</Lunch>
</content>
<content>
<Date>2/7/2013
</Date>
<Breakfast>WG french toast sticks (4), sausage links, fruit, juice, milk
</Breakfast>
<Lunch>salisbury steak, black eyed peas, creamed potatoes with gravy, greens-MC, spring mixed salad, WW cornbread, fruit, juice, milk
</Lunch>
</content>
<content>
<Date>2/8/2013
</Date>
<Breakfast>WG breakfast bagel, yogurt, fruit, juice, milk
</Breakfast>
<Lunch>BBQ rib portion on WG bun, sweet potato fries or yams, romaine garden salad, fruit, juice, milk
</Lunch>
</content>
<content>
<Date>2/11/2013
</Date>
<Breakfast>Mardi Gras Holiday - No School
</Breakfast>
<Lunch />
</content>
</Contents>

并打电话给NodeList nl = doc.getElementsByTagName("Content");

【讨论】:

  • 也使用 nl.getLength();获取节点列表大小的方法
  • for 循环只重复一次。
  • sax解析器是否可以通过保持相同的xml文件来实现
  • 是的,但我不应该更改 xml 文件。因为其他应用程序使用相同的服务