从节点内的节点获取值

时间:2013-11-24 14:33:04

标签: java android xml

抱歉我的英语。 我是android和xml的新手,现在我遇到了xml的问题。 我已经解析了xml文件,但现在我遇到了这个问题:

<available>
<item>
<description>Hello</description>
<numbers>
<number id="001" name="John">...</number>
<number id="002" name="Jack">...</number>
<number id="003" name="Jim">...</number>
</numbers>
</item>

<item>
<description>Hello</description>
<numbers>
<number id="001" name="John">...</number>
<number id="002" name="Jack">...</number>
<number id="003" name="Jim">...</number>
</numbers>
</item>

</available>

现在,我正在创建2个对象:Item和ItemNumber。 项目包含:字符串描述,矢量 ItemNumber包含:String id,String name

何我可以解析这个xml? 我正在尝试这种方式:

private Vector<ItemNumber> issueNumber = new Vector<ItemNumber>();
private Vector<Item> itemFather = new Vector<Item>();

Document doc = loadXMLFromString(stringXML[1]);
                NodeList elementi = doc.getElementsByTagName("item");

                for (int i = 0; i < elementi.getLength(); i++) {
                    Element item = (Element) elementi.item(i);
                    String description = ((Element) item.getElementsByTagName(
                            "description").item(0)).getTextContent();
                    itemNumber = new Vector<ItemNumber>();

                    NodeList nodeIssue = doc.getElementsByTagName("number");

                    for (int y = 0; y < nodeIssue.getLength(); y++) {
                        Element elemIssue = (Element) nodeIssue.item(y);
                        String number_id = getSubElement(elemIssue, "number",
                                "id");
                        String number_name = getSubElement(elemIssue,
                                "number", "edizione");
                        this.itemNumber.add(new ItemNumber(number_id,
                                number_name));
                    }


                    this.itemFather.add(new Item(description,
                            itemNumber));
                }

这是getSubElement函数:

public static String getSubElement(Element eElement, String tag,
            String valore) {
        String returnVal = "";
        Node eNode;
        int NumOFItem = eElement.getElementsByTagName(tag).getLength();
        for (int y = 0; y < NumOFItem; y++) {
            eNode = eElement.getElementsByTagName(tag).item(y);
            NamedNodeMap attributes = eNode.getAttributes();
            for (int g = 0; g < attributes.getLength(); g++) {
                Attr attribute = (Attr) attributes.item(g);
                try {
                    returnVal = eNode.getAttributes().getNamedItem(valore)
                            .getNodeValue();
                } catch (Exception e) {
                    returnVal = e.toString();
                }
            }
        }
        return returnVal;
    }

感谢您的帮助!

0 个答案:

没有答案