我开始解析xml文档并提出问题:如何在Java上获得特定的XML元素参数值?
XML文档:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
<keyword name="text123">
<profile num="1">
<url>http://www.a.com</url>
<field-1 param="">text</field-1>
<filed-2 param="">text</field-2>
</profile>
<profile num="2">
<url>http://www.b.com</url>
<field-1 param="">text</field-1>
<filed-2 param="">text</field-2>
</profile>
</keyword>
<keyword name="textabc123">
<profile num="1">
<url>http://www.1a.com</url>
<field-1 param="">text</field-1>
<filed-2 param="">text</field-2>
</profile>
<profile num="2">
<url>http://www.1b.com</url>
<field-1 param="">text</field-1>
<filed-2 param="">text</field-2>
</profile>
</keyword>
</data>我在Java上编写的代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File xml_file=new File("file.xml");
if (xml_file.isFile() && xml_file.canRead()) {
Document doc = builder.parse(xml_file);
Element root = doc.getDocumentElement();
NodeList nodel = root.getChildNodes();
for (int a = 0; a < nodel.getLength(); a++) {
String data = /* code i don't know to write*/
System.out.println(data);
}
} else {}我想输出到控制台元素“关键字”参数"name“值:
text123
和
text123abc
帮帮忙,谢谢。
发布于 2011-01-21 12:23:39
Node node = nodel.item(a);
if(node instanceof Element) {
data = ((Element)node).getAttribute("name");
System.out.println(data);
}发布于 2011-01-21 12:30:55
您可以使用XPath
InputStream is = getClass().getResourceAsStream("somefile.xml");
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = xmlFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.parse(is);
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
String text123 = (String) xpath.evaluate("/data/keyword[1]/@name", xmlDoc, XPathConstants.STRING);
String textabc123 = (String) xpath.evaluate("/data/keyword[2]/@name", xmlDoc, XPathConstants.STRING);发布于 2011-01-21 12:26:12
节点列表包含节点,这些节点实际上是子接口(元素、文本等)的实例。
因此,这一守则应适用于:
Node node = nodel.item(a);
if (node instanceof Element) {
Element e = (Element) node;
System.out.println(e.getAttribute("name");
}https://stackoverflow.com/questions/4758685
复制相似问题