我在使用 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();
}
}
}