如何使用java制作动态xml

时间:2010-12-14 09:29:01

标签: java xml

我有一个固定的XML模板,节点可能会根据数据增加。 如果我有一个固定的模板。如何在提供父节点名时迭代所有子节点? 我可以根据xpath制作XML吗?

我有以下代码: -

Map map = hm(); 
            Set set = map.entrySet(); 
            // Get an iterator 
            Iterator it = set.iterator(); 
            // Display elements 
            while(it.hasNext()) { 
                Map.Entry me = (Map.Entry)it.next(); 
                if (check) {
                    xpath_String+= "|"+me.getKey(); 
                }else {
                    xpath_String+= me.getKey();
                    check = true;
                }           
            }

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true); 
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        //xml file name acts as template
        Document doc = builder.parse("template.xml"); 


        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath(); 
        XPathExpression expr = xpath.compile(xpath_String);  
        Object result = expr.evaluate(doc, XPathConstants.NODESET); 
        NodeList nodes = (NodeList) result; 
        System.out.println("Total number of tokens: "+nodes.getLength());
        //for (int i = 0; i < nodes.getLength(); i++) {

        int i=0;

        StringTokenizer st = new StringTokenizer(xpath_String,"|");

        while (st.hasMoreElements()) {
            String val = (String) st.nextElement();
            if(hm().containsKey(val)){
                System.out.println("Node value is: "+nodes.item(i).getNodeName());
                nodes.item(i).setTextContent(hm().get(val).toString());
                i++;
            }
        }
        //}

        //write the content into xml file
         TransformerFactory transformerFactory = TransformerFactory.newInstance();
         Transformer transformer = transformerFactory.newTransformer();
         DOMSource source = new DOMSource(doc);
         // generating the output file name
         StreamResult finalResult =  new StreamResult(new File("newfxml.xml"));
         transformer.transform(source, finalResult);

         //making a string for the dom
         StringWriter writer = new StringWriter();
         StreamResult stResult = new StreamResult(writer);
         transformer.transform(source, stResult);

这里我有一个固定的模板,我是一张地图。从地图我得到xpath及其相应的值。只有模板xml中的节点都没有重复,这才有效。所以我想知道当我得到一个可重复的组件时,是否有任何方法可以迭代整个xml节点块。 有这样的解决方案吗? 或者我需要改变我打算继续进行的方式?

1 个答案:

答案 0 :(得分:1)

如果你想枚举一个节点的所有子节点,你只需要让你的父节点得到类似'Element parent = root.getChild(“parentNodeName”)'的东西,然后你就可以枚举具有相同方法的子节点'列出children = parent.getChildren(“childName”)'。

    Document doc = null;
    SAXBuilder sxb = new SAXBuilder();
    try {
        doc = sxb.build(new File(MyXmlFilePath));
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();
    List<Element> nodes = root.getChildren("myNode");
    Iterator<Element> it = nodes.iterator();
    while(it.hasNext())
    {
        Element currentNode = it.next();
        // node treatment here
    }

Anhuin。