Xml to java解析基于属性值到单独的变量

时间:2014-04-01 07:54:55

标签: java xml xml-parsing converter xstream

我正在研究XML到java解析。我的情况类似于此。

我需要在一个成员中使用属性PERMANENT="Y"解析所有 EMPLOYEE 元素,并在另一个成员中解析属性PERMANENT="N"

<EMPLOYEE PERMANENT="Y">
    <DETAILS NAME="AA"  ID="1"  AGE="28" />
    <DETAILS NAME="BB"  ID="2"  AGE="29" />
</EMPLOYEE>
<EMPLOYEE PERMANENT="N">
   <DETAILS NAME="CC"  ID="3"  AGE="28" />
    <DETAILS NAME="DD"  ID="4"  AGE="29" />
</EMPLOYEE>

爪哇

public class Employee
{

   // @XStreamAlias("EMPLOYEE") and attribute PERMANENT="Y"
    private Details permanentEmployee;

   // @XStreamAlias("EMPLOYEE") and attribute PERMANENT="Y"
    private Details tempEmployee;

}

我不知道该怎么做。

有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class ParseXML {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse (new File("D:/test.xml"));

        NodeList elt = doc.getElementsByTagName("EMPLOYEE");
        for (int k = 0; k < elt.getLength(); k++) {
            Node firstNode3 = elt.item(k);
            Element elt1 = (Element) firstNode3;
            String att=elt1.getAttribute("PERMANENT");
            System.out.println("\n\nPERMANENT: "+att);

            NodeList nodes = elt1.getElementsByTagName("DETAILS");
            for(int i=0;i<nodes.getLength();i++){
                Node childNode = nodes.item(i);
                Element elt2 = (Element) childNode;
                System.out.println("---"+elt2.getNodeName());
                System.out.println("NAME:"+elt2.getAttribute("NAME"));
                System.out.println("ID:"+elt2.getAttribute("ID"));
                System.out.println("AGE:"+elt2.getAttribute("AGE"));
            }

        }//end of for
    }