[英]Accessing values using XML keyname
I have XML similar to this contained in a Document
object ( org.w3c.dom.Document
) in my code: 我在代码中的
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>
I would like to be able to access each key
node and print out its value, and be able to print out each value with its corresponding keyname
我希望能够访问每个
key
节点并打印出其值,并能够打印出每个值及其对应的keyname
I have never worked with XML using keyname
before, how do I access these values? 我以前从未使用过使用
keyname
XML,如何访问这些值?
It's very simple using DOM parser using getAttributes().getNamedItem("keyname")
method. 使用DOM解析器的
getAttributes().getNamedItem("keyname")
方法非常简单。
sample code: 样例代码:
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");
}
}
output: 输出:
keyname="info" value:
keyname="name" value:
keyname="address" value:
keyname="id" value: 13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.