我想用Java的DocumentBuilder解析这个XML文件:
<GLS version="1" type="telegram">
<telegram version="1">
<params>
<id_batch>60500.012.16"</id_batch>
<supplier value="HUGO"/>
</params>
</telegram>
</GLS>
读取id_batch标签没问题,但现在可以给供应商标签的值吗?
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("params");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
System.out.println("\nCurrent Element: " + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("-1-> " + eElement.getElementsByTagName("id_batch").item(0).getTextContent());
System.out.println("-2-> " + eElement.getElementsByTagName("supplier").item(0).getAttribute("value"));
}
}
出现此错误: 无法解析方法'getAttribute(java.lang.String)'
我做错了!但是什么?
由于
答案 0 :(得分:3)
使用您自己的示例,您只需要调用getAttribute(..)。所以添加以下内容:
System.out.println("-3-> " + eElement.getElementsByTagName("supplier").item(0).getAttribute("value"));
答案 1 :(得分:1)
value="HUGO"
是getElementsByTagName供应商的一个属性......所以你试图弄错...
尝试改为:
System.out.println("value : " + eElement.getAttribute("supplier").getAttribute("value"));