3

在我的应用程序中,我有一个 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>我不知道如何从TAG 中提取数据。你可以看到我为 DOM 解析器开发的代码。这是我的 DOM 解析器<prepTime><instructions><ingredients>

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;
    }
}
4

2 回答 2

2

您需要ingredients像为recipe标记那样迭代子节点。

但更简单的方法是使用XPath

于 2013-09-28T18:03:55.763 回答
0

您可以如下更改您的代码。

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));
}

希望这对你有用

于 2013-10-07T12:02:37.760 回答