找到你要的答案

Q:Read all tags and values from XML android java

Q:读取XML Android java所有的标签和值

I have been searching for reading XML tags and its values, what i can find is read the values using tag names, but without knowing the tag names is it possible to read all values, if so please explain me

SAMPLE XML

<menu>
        <item>
            <id>1</id>    
            <name>test1</name>
            <cost>155</cost>
            <description>Single</description>
        </item> 
        <item>
            <id>2</id>    
            <name>test2</name>
            <cost>225</cost>
            <description>double</description>
        </item> 
        <item>
            <id>3</id>    
            <name>test3</name>
            <cost>110</cost>
            <description>long</description>
        </item> 
        <item>
            <id>4</id>    
            <name>test4</name>
            <cost>155</cost>
            <description>float</description>
        </item> 
        <item>
            <id>5</id>    
            <name>test5</name>
            <cost>445</cost>
            <description>integer</description>
        </item> 

</menu>

我一直在寻找阅读XML标签和它的值,我可以找到的是使用标签名称读取值,但不知道标签的名称是否有可能读取所有值,如果是,请解释我

示例XML

<menu>
        <item>
            <id>1</id>    
            <name>test1</name>
            <cost>155</cost>
            <description>Single</description>
        </item> 
        <item>
            <id>2</id>    
            <name>test2</name>
            <cost>225</cost>
            <description>double</description>
        </item> 
        <item>
            <id>3</id>    
            <name>test3</name>
            <cost>110</cost>
            <description>long</description>
        </item> 
        <item>
            <id>4</id>    
            <name>test4</name>
            <cost>155</cost>
            <description>float</description>
        </item> 
        <item>
            <id>5</id>    
            <name>test5</name>
            <cost>445</cost>
            <description>integer</description>
        </item> 

</menu>
answer1: 回答1:

I have been tinkering with the same problem and think I have found the solution:

private void listNodes(NodeList nodeList){


    // Loop through the node list
    for (int temp = 0; temp < (nodeList != null ? nodeList.getLength() : 0); temp++) {

        Node node = nodeList.item(temp);
        // if node is element
        if (node.getNodeType() == Node.ELEMENT_NODE) {

            // create element from node
            Element element = (Element) node;

            // get tag name from element
            Log.d("tag", "tag/node: " + element.getTagName());

            // if node has children repeat the loop until last child
            if (node.hasChildNodes()) {

                listNodes(node.getChildNodes());

            }

        }

    }

}

This will give you the tags of ALL nodes, now you just have to implement this to the desired level of your xml. Once you have the tags put them in an array and get elements from them.

EDIT:

ok so I've played with this for a while and got some interesting results. First of all I have my xmls set up so that each row is in an <item> tag so there is no confusion there. This is what I use to get the node list:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

    DocumentBuilder builder = dbf.newDocumentBuilder();
    // input stream of any kind, can be local or from URL
    Document doc = builder.parse(new InputSource(inputStream));
    doc.getDocumentElement().normalize();

    // rowNodeName in my case is "item" so you can change this to anything suitable
    nodeList = doc.getElementsByTagName(rowNodeName);

} catch (ParserConfigurationException | IOException | SAXException e) {

    e.printStackTrace();

}

So now that you have the node list just do something like this:

// a global object for tag strings
nodeNames = new ArrayList<>();

// populate tag list by reading them from first element
listNodes(nodeList.item(0).getChildNodes(), false);

// list nodes, notice the second parameter is boolean
listNodes(nodeList,true);

And the final listNodes method is as follows:

private void listNodes(NodeList list, boolean getValues) {

    for (int temp = 0; temp < (list != null ? list.getLength() : 0); temp++) {

        Node node = list.item(temp);

        if (node.getNodeType() == Node.ELEMENT_NODE) {

            Element element = (Element) node;

            // if you want values then you loop through the tag names and get node values for those tags
            if (getValues) {

                Bundle bundle = new Bundle();

                for(int i = 0; i< nodeNames.size(); i++){

                    bundle.putString(nodeNames.get(i), getNode(nodeNames.get(i),element));

                }

                xmlTableRows.add(bundle);

            } else {
                /// if you want tags just read them from node
                nodeNames.add(element.getTagName());

            }

        }

    }

}

The getNode method:

private static String getNode(String tag, Element element) {

    NodeList nlList = element.getElementsByTagName(tag).item(0)
            .getChildNodes();

    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();

}

So now you dont depend on knowing how many tags there are in an xml or what their names are. Hope this helps.

我一直摆弄着同样的问题,认为我已经找到了解决方案:

private void listNodes(NodeList nodeList){


    // Loop through the node list
    for (int temp = 0; temp < (nodeList != null ? nodeList.getLength() : 0); temp++) {

        Node node = nodeList.item(temp);
        // if node is element
        if (node.getNodeType() == Node.ELEMENT_NODE) {

            // create element from node
            Element element = (Element) node;

            // get tag name from element
            Log.d("tag", "tag/node: " + element.getTagName());

            // if node has children repeat the loop until last child
            if (node.hasChildNodes()) {

                listNodes(node.getChildNodes());

            }

        }

    }

}

这将给你所有节点的标签,现在你只需要实现你的XML的期望水平。一旦你有了标签,把它们放进一个数组并从中获取元素。

编辑:

好吧,我玩了一会儿,得到了一些有趣的结果。首先,我有我的XML设置,每一行是在& lt;项目>;标签,所以没有混乱有。这是我用来获取节点列表:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

    DocumentBuilder builder = dbf.newDocumentBuilder();
    // input stream of any kind, can be local or from URL
    Document doc = builder.parse(new InputSource(inputStream));
    doc.getDocumentElement().normalize();

    // rowNodeName in my case is "item" so you can change this to anything suitable
    nodeList = doc.getElementsByTagName(rowNodeName);

} catch (ParserConfigurationException | IOException | SAXException e) {

    e.printStackTrace();

}

所以现在你有节点列表只是做这样的事情:

// a global object for tag strings
nodeNames = new ArrayList<>();

// populate tag list by reading them from first element
listNodes(nodeList.item(0).getChildNodes(), false);

// list nodes, notice the second parameter is boolean
listNodes(nodeList,true);

最后listnodes方法如下:

private void listNodes(NodeList list, boolean getValues) {

    for (int temp = 0; temp < (list != null ? list.getLength() : 0); temp++) {

        Node node = list.item(temp);

        if (node.getNodeType() == Node.ELEMENT_NODE) {

            Element element = (Element) node;

            // if you want values then you loop through the tag names and get node values for those tags
            if (getValues) {

                Bundle bundle = new Bundle();

                for(int i = 0; i< nodeNames.size(); i++){

                    bundle.putString(nodeNames.get(i), getNode(nodeNames.get(i),element));

                }

                xmlTableRows.add(bundle);

            } else {
                /// if you want tags just read them from node
                nodeNames.add(element.getTagName());

            }

        }

    }

}

的getnode方法:

private static String getNode(String tag, Element element) {

    NodeList nlList = element.getElementsByTagName(tag).item(0)
            .getChildNodes();

    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();

}

所以现在你不需要知道有多少标签在一个XML或他们的名字是。希望这有助于。

answer2: 回答2:

Try this out.

 DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();

    Document doc = dbf.newDocumentBuilder().parse(file);
    doc.getDocumentElement().normalize(); // Not Mandatory

    NodeList elements=doc.getElementsByTagName("*");
    for (int i=0; i<elements.getLength(); i++) 
    {
        // Get element
        Element elem = (Element)elements.item(i);
        System.out.println(elem.getNodeName());
    }

试试这个。

 DocumentBuilderFactory a = DocumentBuilderFactory.newInstance();

    Document doc = dbf.newDocumentBuilder().parse(file);
    doc.getDocumentElement().normalize(); // Not Mandatory

    NodeList elements=doc.getElementsByTagName("*");
    for (int i=0; i<elements.getLength(); i++) 
    {
        // Get element
        Element elem = (Element)elements.item(i);
        System.out.println(elem.getNodeName());
    }
java  android