【问题标题】:Get text from xml - Android从 xml 获取文本 - Android
【发布时间】:2015-03-18 20:28:03
【问题描述】:

我有这个xml在线http://64.182.231.116/~spencerf/test.xml

我正在尝试获取两个文本值Assorted CerealYogurt Parfait (2)。这是我目前解析它的方式,我得到了我想要的值以及当时的所有值,所有数字等,但我只想得到名字,我正在努力如何做到这一点,任何帮助或指导都会很棒。这是我的代码:

String currentDay = "";
        String currentMeal = "";
        String counter = "";
        String icon1 = "";

        LinkedHashMap<String, List<String>> itemsByCounter = new LinkedHashMap<String , List<String>>();
        List<String> items = new ArrayList<String>();



        while (eventType != XmlResourceParser.END_DOCUMENT) {
            String tagName = xmlData.getName();

            switch (eventType) {
                case XmlResourceParser.START_TAG:
                    if (tagName.equalsIgnoreCase("day")) {
                        currentDay = xmlData.getAttributeValue(null, "name");
                    }
                    if (tagName.equalsIgnoreCase("meal")) {
                        currentMeal = xmlData.getAttributeValue(null, "name");
                    }
                    if (tagName.equalsIgnoreCase("counter") && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
                        counter = xmlData.getAttributeValue(null, "name");
                    }
                    if (tagName.equalsIgnoreCase("name") && counter != null && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
                        icon1 = xmlData.getAttributeValue(null, "icon1");
                        Log.i(TAG, "icon1: " + icon1);
                    }

                    break;
                case XmlResourceParser.TEXT:
                    if (currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal) && counter !=(null)) {
                        if (xmlData.getText().trim().length() > 0) {
                            //Here gets everything but I just want 2 names
                            Log.i(TAG, "data: " + xmlData.getText());
                            items.add(xmlData.getText().trim().replaceAll(" +", " "));

                        }

                    }
                    break;

                case XmlPullParser.END_TAG:
                    if (tagName.equalsIgnoreCase("counter")) {
                        if (items.size() > 0) {
                            itemsByCounter.put(counter, items);
                            items = new ArrayList<String>();
                            recordsFound++;
                        }
                    }
                    break;
            }
            eventType = xmlData.next();

因此,正如您在我的代码中的注释中看到的那样,我得到了名称标签下的所有内容,但我只想要名称的值,而不是所有其他内容。

【问题讨论】:

  • 在问题本身中包含您的 xml 示例。然后,查看您的问题的人始终可以使用它。

标签: java android xml parsing


【解决方案1】:

您需要将名称存储在其自己的子元素中(这意味着在营养成分之前添加一个结束标签)。在每个dish 下,你可以有这个:

<name>Assorted Cereal</name>
<nutrition_facts> ... </nutrition_facts>

【讨论】:

    【解决方案2】:

    未经测试,但可以按照以下方式进行:

    List<Nutrition_Facts> nutrition_facts = new ArrayList<Nutrition_Facts>();
    XMLDOMParser parser = new XMLDOMParser();
    AssetManager manager = context.getAssets();
    InputStream stream;
    try {       
        stream = manager.open("test.xml"); //need full path to your file here - mine is stored in assets folder
        Document doc = parser.getDocument(stream);
    }catch(IOException ex){
        System.out.printf("Error reading map %s\n", ex.getMessage());
    }
    NodeList nodeList = doc.getElementsByTagName("nutrition_facts");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element e = (Element) nodeList.item(i);
        String name; 
        if (elementName.equals(e.getAttribute("Assorted Cereal"))){
            name = e.getAttribute("name");
            //do some stuff
    
        }
     }
    
    //XMLDOMParser Class
    public class XMLDOMParser {
        //Returns the entire XML document 
        public Document getDocument(InputStream inputStream) {
            Document document = null;
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder db = factory.newDocumentBuilder();
                InputSource inputSource = new InputSource(inputStream);
                document = db.parse(inputSource);
            } 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 document;
        }
    
        /*
         * I take a XML element and the tag name, look for the tag and get
         * the text content i.e for <employee><name>Kumar</name></employee>
         * XML snippet if the Element points to employee node and tagName 
         * is name I will return Kumar. Calls the private method 
         * getTextNodeValue(node) which returns the text value, say in our 
         * example Kumar. */
        public String getValue(Element item, String name) {
            NodeList nodes = item.getElementsByTagName(name);
            return this.getTextNodeValue(nodes.item(0));
        }
    
        private final String getTextNodeValue(Node node) {
            Node child;
            if (node != null) {
                if (node.hasChildNodes()) {
                    child = node.getFirstChild();
                    while(child != null) {
                        if (child.getNodeType() == Node.TEXT_NODE) {
                            return child.getNodeValue();
                        }
                        child = child.getNextSibling();
                    }
                }
            }
            return "";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-28
      • 2015-05-19
      • 2020-06-12
      • 2014-08-10
      • 2013-07-06
      • 2012-03-23
      • 2015-06-28
      相关资源
      最近更新 更多