我在使用dom从xml读取数据时遇到问题。我不知道为什么“System.out.println(nNode.getChildNodes()。item(0).hasAttributes());”返回false ...在我的xml文件中,此节点包含属性。你能帮帮我吗?
这是我的代码:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XmlParser {
private String[] linia;
private String[] wariant;
private String[] przystanek;
private String[] tabliczka;
private String[] dzien;
private String[] godz;
private String[] min;
public void readXml() {
try {
File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("linia");
System.out.println("-----------------------");
Node nNode = nList.item(0);
linia = new String[nNode.getAttributes().getLength()];
System.out.println(nNode.getAttributes().getLength());
int i = 0;
while (i < nNode.getAttributes().getLength()) {
linia[i] = nNode.getAttributes().item(i) + "";
System.out.print(linia[i] + " ");
i++;
}
wariant = new String[nNode.getChildNodes().getLength()];
System.out.println();
System.out.println(nNode.getChildNodes().getLength());
System.out.println(nNode.getNodeName());
int j = 0;
System.out.println(nNode.getChildNodes().item(0).hasAttributes());
while (j < nNode.getChildNodes().getLength()) {
wariant[j] = nNode.getChildNodes().item(j).getAttributes()
.item(0)
+ "";
// if(wariant[j].toString()!=null)
System.out.println(" " + wariant[j]);
j++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
您是否检查了索引1处的子节点?我的猜测是你的解析器将标签(换行符,制表符,空格)之间的所有字符视为CDATA,并将它们解析为没有属性的CDATA节点。