使用XML keyname访问值

时间:2014-08-01 15:37:34

标签: java xml xml-parsing

我的代码中包含Document对象(org.w3c.dom.Document)中的XML与此类似:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <key keyname="info"> </key>
    <key keyname="name"/>
    <key keyname="address"/>
    <key keyname="id">13</key>
</root>

我希望能够访问每个key节点并打印出其值,并能够打印出每个值及其对应的keyname

之前我从未使用keyname使用过XML,如何访问这些值?

1 个答案:

答案 0 :(得分:1)

使用getAttributes().getNamedItem("keyname")方法使用DOM解析器非常简单。

示例代码:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class SpringXMLParser {

    public static void parse(String file) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.parse(new FileInputStream(file));
        Element root = doc.getDocumentElement();
        org.w3c.dom.NodeList nodeList = root.getElementsByTagName("key");
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.print(((Node) nodeList.item(i))
                     .getAttributes().getNamedItem("keyname"));
            System.out.println("\tvalue: "+((Node) nodeList.item(i)).getTextContent());
        }

    }

    public static void main(String args[]) throws Exception {
        parse("resources/xml5.xml");
    }
}

输出:

keyname="info"      value:  
keyname="name"      value: 
keyname="address"   value: 
keyname="id"        value: 13