读取并打印出XML文件到控制台

时间:2017-11-12 11:03:32

标签: java xml

我需要从我创建的xml文件中打印出一些属性。

到目前为止,我受到了MKyoung的启发,并在他的作品中做了一些改变。但我无法获得xml属性。我想打印出""中的名字。和得分。

<score name="Rasmus" score="10000"/>

获取它的代码是:

public void readXMLFile(){
    try {

    File fXmlFile = new File("highscore.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    System.out.println("Root element : " + doc.getDocumentElement().getNodeName());

    NodeList nList = doc.getElementsByTagName("Highscore");

    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element : " + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            System.out.println("Name : " + eElement.getAttribute("score"));


        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

我的名为highscore.xml的xml文件包含:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Highscore>
  <score name="Rasmus" score="10000"/>
  <score name="Søren" score="6000"/>
  <score name="Niclas" score="5000"/>
</Highscore>

2 个答案:

答案 0 :(得分:0)

你可以使用像simple-xml这样的开源库。

private Serializer serializer = new Persister();

// Reading
(YOUROBJECT) serializer.read(YOUROBJECT.class, new File(path));
// Writing
serializer.write(YOUROBJECT, file);

答案 1 :(得分:0)

我已经通过添加两行来编辑代码。检查下面。基本上,您必须遍历下一级节点。

<强>码

public void readXMLFile(){
    try {

    File fXmlFile = new File("highscore.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("Highscore");
    Node child = nList.item(0);
    NodeList nL = child.getChildNodes();    
    System.out.println("----------------------------");
    int i=1;
    for (int temp = 0; temp < nL.getLength(); temp++) {
        Node nNode = nL.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            System.out.println(i+ ","+ eElement.getAttribute("name") +","+ eElement.getAttribute("score"));
                i++;
        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

<强>输出:

Root element : Highscore
----------------------------
1,Rasmus,10000
2,Søren,6000
3,Niclas,5000