【问题标题】:Xml to java parsing based on attribute value to a separate variable基于属性值的xml到java解析到单独的变量
【发布时间】:2014-05-11 20:54:59
【问题描述】:

我正在研究 XML 到 java 的解析。我有一个类似的场景。

我需要解析所有 EMPLOYEE 元素在一个成员中具有属性 PERMANENT="Y",在另一个成员中具有属性 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>

Java

public class Employee
{

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

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

}

我不知道该怎么做。

谁能帮帮我。

【问题讨论】:

    标签: java xml xml-parsing converter xstream


    【解决方案1】:
    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
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2013-12-22
      • 2017-05-02
      • 1970-01-01
      相关资源
      最近更新 更多