Java如何根据XML文件

时间:2016-11-12 19:06:35

标签: java xml

这是xml文件。

<columns>
  <c id="3">c</c>
  <b id="2">b</b>
  <a id="1">a</a>
  <d id="4">d</d>
  <e id="5">e</e>
</columns>

我必须将内容存储在一个数组中并使用循环来显示它们。
&#34; id&#34;应按升序排列。
我如何获得内容&#34; a&#34;在标签中根据&#34; id&#34;在Java?

预期产量应为:

a
b
c
d
e

此处更新的xml文件

我只想要内容a-e。

<data>
  <columns>
    <c id="3">Content of c</c>
    <b id="2">Content of b</b>
    <a id="1">Content of a</a>
    <d id="4">Content of d</d>
    <e id="5">Content of e</e>
  </columns>
  <xyz id="1">
    <hi>hi</hi>
  </xyz>
  <xyz id="2">
    <bye>bye</bye>
  </xyz>
</data>

1 个答案:

答案 0 :(得分:0)

------------------------------ ORIGINAL XML ------------ ------------------

首先,XML文件有错误,最后一个元素是&#34; / columns&#34;:

<?xml version="1.0" encoding="UTF-8"?>
<columns>
  <c id="3">Content of c</c>
  <b id="2">Content of b</b>
  <a id="1">Content of a</a>
  <d id="4">Content of d</d>
  <e id="5">Content of e</e>
</columns>

然后,试试这个:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;


public class orderXML {

    public static void main(String argv[]) {

        try {

            File fXmlFile = new File("src/Content.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.getDocumentElement().getChildNodes();

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println("    READ ORDER              ");
            System.out.println("++++++++++++++++++++++++++++");     

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

                Node nNode = nList.item(temp);          

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());
                    Element eElement = (Element) nNode;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());
                }
            }           

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println("    ID ORDER                ");
            System.out.println("++++++++++++++++++++++++++++");

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

                Node node=returnNodeByValue(nList, "id", String.valueOf(temp));

                if(node!=null && node.getNodeType() == Node.ELEMENT_NODE){
                    System.out.println("\nCurrent Element :" + node.getNodeName());
                    Element eElement = (Element) node;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());   
                }               
            }       
        } catch (Exception e) {
            e.printStackTrace();
        }
      }

    /**
     * Returns a Node by attribute name and attribute value.
     * @param nodeList  NodeList where we find the node
     * @param attributeName Attribute name to search
     * @param attributeValue Attribute name to search
     * @return If exists a node with attributeName and attributeValue returns this Node,
     *      if not exists, returns null
     */
    private static Node returnNodeByValue(NodeList nodeList, String attributeName, String attributeValue) {
        for (int temp = 0; temp < nodeList.getLength(); temp++) {

            Node nNode = nodeList.item(temp);           

            if (nNode.getNodeType() == Node.ELEMENT_NODE){
                Element eElement = (Element) nNode;
                String returnAttribute = eElement.getAttribute(attributeName);
                if(returnAttribute.equals(attributeValue)){
                    return nNode;
                }
            }                           

        }
        return null;
    }
}

输出:

根元素:列

++++++++++++++++++++++++++++

READ ORDER  

++++++++++++++++++++++++++++

当前元素:c Id:3 内容:c的内容

当前元素:b Id:2 内容:b的内容

当前元素:a Id:1 内容:

的内容

当前元素:d Id:4 内容:d的内容

当前元素:e Id:5 内容:e的内容

++++++++++++++++++++++++++++

ID ORDER    

++++++++++++++++++++++++++++

当前元素:a Id:1 内容:

的内容

当前元素:b Id:2 内容:b的内容

当前元素:c Id:3 内容:c的内容

当前元素:d Id:4 内容:d的内容

当前元素:e Id:5 内容:e的内容

------------------------------ MODIFIED XML ------------ ------------------

XML文件:

<data>
  <columns>
    <c id="3">Content of c</c>
    <b id="2">Content of b</b>
    <a id="1">Content of a</a>
    <d id="4">Content of d</d>
    <e id="5">Content of e</e>
  </columns>
  <xyz id="1">
    <hi>hi</hi>
  </xyz>
  <xyz id="2">
    <bye>bye</bye>
  </xyz>
</data>

代码:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.util.ArrayList;

public class orderXML {

    public static void main(String argv[]) {

        try {

            File fXmlFile = new File("src/contentUpdate.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());

            //  1 - Get childrens of root

            NodeList nList = doc.getDocumentElement().getChildNodes();
            NodeList childrenOfColumns = null;
            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);          

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());

                    //  2 - If this element is columns, we store it...

                    if(nNode.getNodeName().equals("columns")){
                        Element eElement = (Element) nNode;
                        childrenOfColumns = eElement.getChildNodes();
                    }
                }
            } 

            //  3 - Finaly we use "childrenOfColumns"

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println(" READ ORDER INSIDE COLUMNS ");
            System.out.println("++++++++++++++++++++++++++++");     

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

                Node nNode = childrenOfColumns.item(temp);          

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("\nCurrent Element :" + nNode.getNodeName());
                    Element eElement = (Element) nNode;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());
                }
            }           

            System.out.println("++++++++++++++++++++++++++++");
            System.out.println(" ID ORDER INSIDE COLUMNS    ");
            System.out.println("++++++++++++++++++++++++++++");

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

                Node node=returnNodeByValue(childrenOfColumns, "id", String.valueOf(temp));

                if(node!=null && node.getNodeType() == Node.ELEMENT_NODE){
                    System.out.println("\nCurrent Element :" + node.getNodeName());
                    Element eElement = (Element) node;
                    System.out.println("Id : " + eElement.getAttribute("id"));
                    System.out.println("Content : " + eElement.getTextContent());   
                }               
            }       
        } catch (Exception e) {
            e.printStackTrace();
        }
      }

    /**
     * Returns a Node by attribute name and attribute value.
     * @param nodeList  NodeList where we find the node
     * @param attributeName Attribute name to search
     * @param attributeValue Attribute name to search
     * @return If exists a node with attributeName and attributeValue returns this Node,
     *      if not exists, returns null
     */
    private static Node returnNodeByValue(NodeList nodeList, String attributeName, String attributeValue) {
        for (int temp = 0; temp < nodeList.getLength(); temp++) {

            Node nNode = nodeList.item(temp);           

            if (nNode.getNodeType() == Node.ELEMENT_NODE){
                Element eElement = (Element) nNode;
                String returnAttribute = eElement.getAttribute(attributeName);
                if(returnAttribute.equals(attributeValue)){
                    return nNode;
                }
            }                           

        }
        return null;
    }
}

输出:

根元素:数据

当前元素:列

当前元素:xyz

当前元素:xyz

++++++++++++++++++++++++++++

阅读内部栏目

++++++++++++++++++++++++++++

当前元素:c Id:3 内容:c的内容

当前元素:b Id:2 内容:b的内容

当前元素:a Id:1 内容:

的内容

当前元素:d Id:4 内容:d的内容

当前元素:e Id:5 内容:e的内容

++++++++++++++++++++++++++++

ID ORDER INSIDE COLUMNS

++++++++++++++++++++++++++++

当前元素:a Id:1 内容:

的内容

当前元素:b Id:2 内容:b的内容

当前元素:c Id:3 内容:c的内容

当前元素:d Id:4 内容:d的内容

当前元素:e Id:5 内容:e的内容