从HashMap创建XML输入数据

时间:2015-04-23 06:08:55

标签: java xml dynamic

我在HashMap中有以下数据:

Map<String, String> data = new HashMap<String, String>();

        data.put("A.B.C.C1.C11", "C11");
        data.put("A.B.C.C1.C12", "C12");
        data.put("A.B.C.C2.C21", "C21");
        data.put("A.B.C.C2.C22", "C22");
        data.put("A.B.C.C3.C31", "C31");
        data.put("A.B.C.D", "D");

我有一个requiremrnt以下面的格式创建XML(预期输出):

<A>
   <B>
      <C>
         <C1>
            <C11>C11</C11>
            <C12>C12</C12>
         </C1>
         <C2>
            <C21>C21</C21>
            <C22>C22</C22>
         </C2>
         <C3>
            <C3>C3</C3>
         </C3>
         <D>D</D>
      </C>
   </B>
</A>

生成输出代码:

<A>
  <B>
    <C>
      <D>
        <C1>
          <C11>
            <C12>
              <C2>
                <C21>
                  <C22>
                    <C3>
                      <C31/>
                    </C3>
                  </C22>
                </C21>
              </C2>
            </C12>
          </C11>
        </C1>
      </D>
    </C>
  </B>
</A>

我写的代码(脏):

public class DynamicXML3 {
    public static   boolean isFirstElemnt=true;
    static Element element = null;
    public static Element mainRoot =null;
    public static void main(String args[]) {

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = docFactory.newDocumentBuilder();
            Document document = builder.newDocument();
            String root,a1="a1";
            Map<String, String> data = new HashMap<String, String>();
            data.put("A.B.C.C1.C11", "C11");
            data.put("A.B.C.C1.C12", "C12");
            data.put("A.B.C.C2.C21", "C21");
            data.put("A.B.C.C2.C22", "C22");
            data.put("A.B.C.C3.C31", "C31");
            data.put("A.B.C.C.D", "D");

            data = new TreeMap<String, String>(data);
            Set set1 = data.entrySet();
            Iterator i1 = set1.iterator();
            while(i1.hasNext()) {
                Map.Entry me1 = (Map.Entry)i1.next();
                System.out.println(me1.getKey() + ": ");
                //System.out.println(me1.getValue());

                //create Buddy XML
                String key= me1.getKey()+"";
                String[] buddyXML= key.split("\\.");

                NodeList rootElementList = document.getElementsByTagName(buddyXML[0]);
                if(!(rootElementList.getLength()>0)){
                    mainRoot = document.createElement(buddyXML[0]);
                    document.appendChild(mainRoot);
                    System.out.println("root created\n");
                }

                for(int i=0; i<buddyXML.length; i++){
                    System.out.println("value: "+buddyXML[i]);
                    NodeList elementList = document.getElementsByTagName(buddyXML[i]);
                    System.out.println("here "+elementList.getLength());
                    System.out.println("creating Node "+buddyXML[i]);
                    if(!(elementList.getLength()>0)){
                        System.out.println("creating Node "+buddyXML[i] + " & main root: "+mainRoot.getNodeName());
                        Element element =createNode(buddyXML[i], document, mainRoot);
                        mainRoot = element;
                    }
                }
                System.out.println("");
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            // Add indentation to outputs
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new File("D://RC/BuddyCode.xml"));
            transformer.transform(source, result);

        } catch (Exception e) {
            System.out.println("Exception: "+e);
        }
    }
    public static void createElement(Element elemnetName, Document document, Object data) {
        Text text =document.createTextNode(data.toString());
        elemnetName.appendChild(text);
    }

    private static Element createNode(String nodeName, Document document,Element rootElement) {
        Element node = document.createElement(nodeName);
        rootElement.appendChild(node);
        return node;
    }
}

这没有按预期工作,我试图改为其他一些appraoch但似乎没有用,有人可以指导我。

注意:HashMap中的数据可能会水平和垂直地增加,这意味着,在运行时我可以拥有任意数量的节点,因此需要创建一个通用代码。建议使用DomParser。

3 个答案:

答案 0 :(得分:0)

在你的代码中,函数调用就像这个Element element =createNode(buddyXML[i], document, mainRoot);一样,而fucntion声明就是createElement(Element elemnetName, Document document, Object data)

参数顺序错误。可能是造成问题。我没有清楚的问题你的问题。但我发现这会导致代码出现问题。所以张贴了它。如果您需要任何进一步的帮助,请告诉我

答案 1 :(得分:0)

我们可以尝试这样的事情:

public class DynamicXML3 {

    private static final String SEPARTOR = "\\.";

    public static void main(String args[]) {

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = docFactory.newDocumentBuilder();
            Document document = builder.newDocument();

            Map<String, String> data = new HashMap<String, String>();
            data.put("A.B.C.C1.C11", "C11");
            data.put("A.B.C.C1.C12", "C12");
            data.put("A.B.C.C2.C21", "C21");
            data.put("A.B.C.C2.C22", "C22");
            data.put("A.B.C.C3.C31", "C31");
            data.put("A.B.C.C.D", "D");

            Iterator<Entry<String, String>> it = data.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry<String, String>)it.next();
                System.out.println(pair.getKey() + " = " + pair.getValue());
                appendElement(document, pair.getKey(), pair.getValue());
                it.remove();
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new File("C:/Users/Desktop/BuddyCode.xml"));
            transformer.transform(source, result);

        } catch (Exception e) {
            System.out.println("Exception: "+e);
        }
    }

    private static void appendElement(Document document, String key, String value) {
        String[] splitedElements = key.split(SEPARTOR);
        for (int i = 0; i < splitedElements.length; i++) {
            NodeList nlst = document.getElementsByTagName(splitedElements[i]);
            if(nlst == null || nlst.getLength() == 0) {
                if(i==0) {
                    document.appendChild(document.createElement(splitedElements[i]));
                } else {
                    (document.getElementsByTagName(splitedElements[i-1]).item(0)).appendChild(document.createElement(splitedElements[i]));
                }
                if(i==(splitedElements.length-1)) {
                    (document.getElementsByTagName(splitedElements[i]).item(0)).appendChild(document.createTextNode(value));
                }
            }
        }
    }

}

答案 2 :(得分:0)

这可以解释我的问题:

static void main(String[] args) throws Exception {
    Map<String,String> data = new HashMap<String, String>();
    data.put("A.B.C.C1.C11", "C11");
    data.put("A.B.C.C1.C12", "C12");
    data.put("A.B.C.C2.C21", "C21");
    data.put("A.B.C.C2.C22", "C22");
    data.put("A.B.C.C3.C31", "C31");
    data.put("A.B.C.C.D", "D"); // should probably be data.put("A.B.C.D", "D"); 

    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = f.newDocumentBuilder();
    Document d = db.newDocument();

    for (Map.Entry<String, String> entry : data.entrySet() ) {
        Node n = d;
        String[] keys = entry.getKey().split("\\.");
        for (String k : keys) {
            NodeList nodes = d.getElementsByTagName(k);
            if ( nodes.getLength() == 0 ) {
                n.appendChild(n = d.createElement(k));
            } else {
                n = nodes.item(0);
            }
        }
        n.appendChild(d.createTextNode(entry.getValue()));
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(d), new StreamResult(System.out));
}