簡體   English   中英

如何解析android-java中的xml?

[英]How to parse xml in android-java?

在我的應用程序中,我有一個XML文件,我想解析XML文件並從XML標記中提取數據。 這是我的XML文件。

<array>

    <recipe>

        <name> Crispy Fried Chicken </name>
        <description> Deliciously Crispy Fried Chicken</description>
        <prepTime>1.5 hours </prepTime>
        <instructions>instruction steps</instructions>

        <ingredients>

            <item>
                <itemName>Chicken Parts</itemName>
                <itemAmount>2 lbs</itemAmount>
            </item>

            <item>
                <itemName>Salt &amp; Peppers</itemName>
                <itemAmount>As teste</itemAmount>
            </item>

        </ingredients>

    </recipe>


    <recipe>

        <name> Bourben Chicken </name>
        <description> A good recipe! A tad on the hot side!</description>
        <prepTime>1 hours </prepTime>
        <instructions>instruction steps</instructions>

        <ingredients>

            <item>
                <itemName>Boneless Chicken</itemName>
                <itemAmount>2.5 lbs</itemAmount>
            </item>

            <item>
                <itemName>Olive Oil</itemName>
                <itemAmount>1 -2 tablespoon</itemAmount>
            </item>

            <item>
                <itemName>Olive Oil</itemName>
                <itemAmount>1 -2 tablespoon</itemAmount>
            </item>

        </ingredients>

    </recipe>

</array>

我使用DOM解析器來解析上面的xml文件,我從<name><description><prepTime><instructions>標簽中提取了數據但是我不知道如何從<ingredients> TAG中提取數據。 您可以看到我為DOM解析器開發的代碼。 這是我的DOM解析器

public class DOMParser 
{

    // parse Plist and fill in arraylist
    public ArrayList<DataModel> parsePlist(String xml)
    {
        final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();

        //Get the xml string from assets XML file
        final Document doc = convertStringIntoXML(xml);

//        final NodeList nodes_array = doc.getElementsByTagName("array");

        //Iterating through the nodes and extracting the data.
        NodeList nodeList = doc.getDocumentElement().getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++)
        {
            Node node = nodeList.item(i);
            if (node instanceof Element)
            {
                DataModel model = new DataModel();

                NodeList childNodes = node.getChildNodes();
                for (int j = 0; j < childNodes.getLength(); j++)
                {


                    Node cNode = childNodes.item(j);
                    if (cNode instanceof Element)
                    {
                        String content = cNode.getLastChild().getTextContent().trim();

                        if(cNode.getNodeName().equalsIgnoreCase("name"))
                            model.setName(content);
                        else if(cNode.getNodeName().equalsIgnoreCase("description"))
                            model.setDescription(content);
                        else if(cNode.getNodeName().equalsIgnoreCase("prepTime"))
                            model.setPrepTime(content);
                        else if(cNode.getNodeName().equalsIgnoreCase("instructions"))
                            model.setInstructions(content);
                    }

                }
                dataModels.add(model);
            }
        }



        return dataModels;
    }



    // Create xml document object from XML String
    private  Document convertStringIntoXML(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;
    }
}

您需要遍歷ingredients像你這樣做的子節點recipe標簽。

但更簡單的方法是使用XPath

您可以更改以下代碼。

public ArrayList<DataModel> parsePlist(String xml)
{
    final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();

    //Get the xml string from assets XML file
    final Document doc = convertStringIntoXML(xml);
    //final NodeList nodes_array = doc.getElementsByTagName("array");

    //Iterating through the nodes and extracting the data.
    NodeList nodeList = doc.getDocumentElement().getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++)
    {
        Node node = nodeList.item(i);
        if (node instanceof Element)
        {
            DataModel model = new DataModel();

            NodeList childNodes = node.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++)
            { 
Node cNode = childNodes.item(j);
                if (cNode instanceof Element)
                {
                    String content = cNode.getLastChild().getTextContent().trim();

                    if(cNode.getNodeName().equalsIgnoreCase("name"))
                        model.setName(content);
                    else if(cNode.getNodeName().equalsIgnoreCase("description"))
                        model.setDescription(content);
                    else if(cNode.getNodeName().equalsIgnoreCase("prepTime"))
                        model.setPrepTime(content);
                    else if(cNode.getNodeName().equalsIgnoreCase("instructions"))
                        model.setInstructions(content);
                    else if(cNode.getNodeName().equalsIgnoreCase("ingredients"))
                     {
                        Element ingredEle = (Element)cNode;
                        NodeList ingredList = ingredEle
                    .getElementsByTagName("ingredients");
                        for (int i = 0; i < ingredList.getLength(); i++) 
                        {
                          Element item = (Element)ingredList.item(i);
                          if(item.hasChildNodes()) 
                          {
                             NodeList itemList = item.getElementsByTagName("item");
                             for (int j = 0; j < itemList.getLength(); j++) 
                             {
                               Element itemEle = (Element)itemList.item(j);
                               if (getNodeValue(itemEle, "itemName") != null)
                               {

                                 String name = getNodeValue(itemEle, "itemName");
                               //set name here
                               }
                               if (getNodeValue(itemEle, "itemAmount") != null)
                               { 

                                 String amount = getNodeValue(itemEle,"itemAmount");
                                //set amount here
                               }
                             }
                          } 
                        }
                     }
                }
     dataModels.add(model);
        }
    }



    return dataModels;
}

private String getNodeValue(Element element, String elementTemplateLoc) {
    NodeList nodes = element.getElementsByTagName(elementTemplateLoc);
    return getTextNodeValue(nodes.item(0));
}

希望這對你有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM