【问题标题】:reading xml - java, dom阅读 xml - java, dom
【发布时间】:2012-04-23 12:42:05
【问题描述】:

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

【问题讨论】:

  • 你能发布你文件的示例内容吗

标签: java xml dom xml-parsing


【解决方案1】:

您是否检查过索引 1 处的子节点?我的猜测是您的解析器将标记(换行符、制表符、空格)之间的所有字符视为 CDATA,并将它们解析为没有属性的 CDATA 节点。

【讨论】:

  • 是的,你是对的。但这对我来说很奇怪。看起来其他所有属性都是空的。为什么它的工作方式如此奇怪?我必须做“j=j+2”。
猜你喜欢
  • 1970-01-01
  • 2013-01-24
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
相关资源
最近更新 更多