简体   繁体   中英

how to make a dynamic xml using java

I have a fixed template of XML and the nodes may increase as per the data. If I have a fixed template. How to iterate all the child nodes when the parent node name is being supplied? Can I make a XML based on the xpath?

I have the follwoing code:-

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);

Here I have a fixed template and I a map. from the map I am getting the xpath and its corresponding values. This hold only good until none of the nodes in the template xml repeats itself. So i was wondering if There is any way I can iterate the whole chunk of xml node when I get a repeatable component. Is there any solution like this ? Or I need to change way I m intending to proceed??

If you want to enumerate all the children of a node, you just need to get your parent node with something like 'Element parent = root.getChild("parentNodeName")' then you can enumerate the children with the same methode 'List 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM