我的代码中包含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,如何访问这些值?
答案 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