简体   繁体   English

从xml填充哈希图(java)

[英]Populating hashmap from xml(java)

my xml looks like: 我的xml看起来像:

<?xml version="1.0"?>
<Grid id = 1>
    <Setup id = "1">
        <Group name = "DrawingRoom">
            <Light id = "1">
                <name>Light1</name>
                <type>ben</type>
                <index>1</index>
            </Light>
            <Light id = "2">
                <name>Light2</name>
                <type>crux</type>
                <index>2</index>
            </Light>
            <Light id = "3">
                <name>Light3</name>
                <type>let</type>
                <index>3</index>
            </Light>
        </Group>
        <Group name = "BedRoom">
            <Light id = "1">
                <name>Light1</name>
                <type>let</type>
                <index>4</index>
            </Light>
        </Group>
    </Setup>
    <Setup id = "2">
        <Group name = "ClubRoom">
            <Light id = "1">
                <name>Light1</name>
                <type>let</type>
                <index>1</index>
           </Light>
       </Group>
   </Setup>
</Grid>

Issue appears when I try to populate hashmap while parsing the xml. 当我尝试在解析xml时填充哈希图时出现问题。 I am using four hashmap each for holding different level of information. 我正在使用四个哈希图,每个哈希图用于保存不同级别的信息。 So the final hashmap consists of hashmap from lower level like setup, group and light with attributes of each level are the keys of respective maps of that level. 因此,最终的哈希图由来自较低级别(如设置,组和灯光)的哈希图组成,每个级别的属性是该级别各自映射的关键。

    public HashMap<String,String> lightContent = new HashMap<String,String>();
    public HashMap<String, HashMap<String,String>> groupContent = new HashMap<String, HashMap<String,String>>();
    public HashMap<String, HashMap<String, HashMap<String,String>>>  setupContent = new HashMap<String, HashMap<String, HashMap<String,String>>>();
    public HashMap<String, HashMap<String, HashMap<String, HashMap<String,String>>>> gridContent = new HashMap<String, HashMap<String, HashMap<String, HashMap<String,String>>>>();

During parsing, the problem comes that as hashmap gets updated so is the automatically the hashmap containing those hashmap. 在解析过程中,问题来了:随着哈希图的更新,包含这些哈希图的哈希图也会自动更新。 So, previous entries are lost when hashmap at lower levels are overwritten. 因此,当较低级别的哈希图被覆盖时,先前的条目将丢失。

I understand that "key" in hashmap points to location of value(here it is another hashmap). 我了解哈希图中的“键”指向值的位置(这里是另一个哈希图)。 Hence, m confused, what next could be done to retrieve all the xml data to hashmap. 因此,很困惑,下一步该怎么做才能将所有xml数据检索到哈希表。 Appreciate your help in this regard !! 感谢您在这方面的帮助!

I am afraid, cant use any external library for this purpose. 恐怕不能为此目的使用任何外部库。 Here is the function: 这是函数:

    public void getSetupConfiguration()
    {
        try {

            File fXmlFile = new File("D:\\SetupConfig.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            NodeList nodeList = doc.getChildNodes();


            if (doc.hasChildNodes())
                {
                for (int count1 = 0; count1 < nodeList.getLength(); count1++) 
                    {
                    System.out.println(nodeList.getLength());
                Node gridNode = nodeList.item(count1);
                if (gridNode.getNodeType() == Node.ELEMENT_NODE) 
                    {
                    String presentNodeName = gridNode.getNodeName();
                    // get node name and value
    //                  System.out.println("\nNode Name =" + presentNodeName);

                    if (presentNodeName.equalsIgnoreCase("Grid"))
                        {
                        if (gridNode.hasChildNodes())
                            {
                            Node setupNode = gridNode.getFirstChild();
                            while (setupNode != null)
                                {
                                if (setupNode.getNodeType() == Node.ELEMENT_NODE) 
                                    {
                                    System.out.println(setupNode.getNodeName());
                                    //Getting group
                                    Node groupNode = setupNode.getFirstChild();
                                    while (groupNode != null)
                                        {
                                        if (groupNode.getNodeType() == Node.ELEMENT_NODE) 
                                            {
                                                System.out.println(groupNode.getNodeName());
                                            // Getting lights
                                            Node lightNode = groupNode.getFirstChild();
                                            while (lightNode != null)
                                                {
                                                if (lightNode.getNodeType() == Node.ELEMENT_NODE)
                                                    {
                                                    System.out.println(lightNode.getNodeName());
                                                    // Getting individual lights
                                                    Node lights = lightNode.getFirstChild();
                                                    while (lights != null)
                                                        {
                                                        if (lights.getNodeType() == Node.ELEMENT_NODE)
                                                            {
                                                            lightContent.put(lights.getNodeName(), lights.getTextContent());
                                                            System.out.println("aaa");
                                                            }
                                                            lights = lights.getNextSibling();


                                                        }
                                                    NamedNodeMap lightMap = lightNode.getAttributes();
                                                    String lightId = "";
                                                    // To get id of Light element
                                                    for (int i = 0; i < lightMap.getLength(); i++ )
                                                    {                                       
                                                        Node lightItem = lightMap.item(i);
                                                        lightId = lightItem.getNodeValue(); 
                                                    }

                                                    groupContent.put(lightId, lightContent);
                                                    System.out.println(groupContent);

                                                    }

                                                    lightNode = lightNode.getNextSibling();

                                                }// Populating Light Node Ends
                                            NamedNodeMap groupMap = groupNode.getAttributes();
                                            String groupName = "";

                                            for (int i = 0; i < groupMap.getLength(); i++ )
                                            {                                       
                                                Node lightItem = groupMap.item(i);
                                                groupName = lightItem.getNodeValue();   
                                            }
                                            setupContent.put(groupName, groupContent);
                                            System.out.println(setupContent);
                                            }
                                            lightContent.clear();
                                            groupContent.clear();
                                            System.out.println(lightContent);
                                            groupNode = groupNode.getNextSibling();
                                        }
                                    }
                                if (setupNode.getNodeType() == Node.ELEMENT_NODE) 
                                {
                                    NamedNodeMap setupMap = setupNode.getAttributes();
                                    String setUpId = "";

                                    for (int i = 0; i < setupMap.getLength(); i++ )
                                    {                                       
                                        Node lightItem = setupMap.item(i);
                                        setUpId = lightItem.getNodeValue(); 
                                    }
                                    gridContent.put(setUpId, setupContent);
                                    System.out.println(gridContent);
                                    setupContent.clear();
                                }

                                setupNode = setupNode.getNextSibling();
                                }

                            }
//                          gridNode = gridNode.getNextSibling();

                            }
                    }
                }
            }
            System.out.println(gridContent);
            }
            catch (Exception e) 
            {
            e.printStackTrace();
            }



        System.out.println("Wow");
    }
    }

Thanks is advance !! 谢谢是提前!

I think you are going down the wrong path. 我认为您走错了路。 If you spend the time to really parse that data into objects, then I would create a real model; 如果您花时间将这些数据真正解析为对象,那么我将创建一个真实的模型。 instead of using Maps of strings. 而不是使用字符串映射。 You see, your current approach is extremely clumsy. 您会看到,您当前的方法非常笨拙。 Those Maps of Maps of Maps are not only hard to populate; 那些Maps of Maps不仅很难填充; they would also be hard to use later on. 他们以后也将很难使用。 Although it is not directly "visible" - your XML data is structured . 尽管它不是直接“可见”的-您的XML数据是结构化的 And by pushing that "blindly" into Maps, you are making a lot of that structure harder to acquire. 通过将其“盲目地”推入“地图”,您将使很多这种结构变得难以获得。

What I mean is: on the lowest level, you are dealing with Lights . 我的意思是:从最底层讲,您正在处理Lights So why don't you create a Light class that contains the corresponding attributes? 那么,为什么不创建一个包含相应属性的Light 呢? But not as raw strings, but already converted into their more specific types. 但不是作为原始字符串,而是已经转换为它们的更特定的类型。 And then you would not push Lights into a Map, but into a List - as they are already coming in that order. 然后,您不会将Lights推送到Map中,而是将其推送到List中 -因为它们已经按照该顺序排列了。

And then you should use existing technologies such as JAXB to turn your XML data into "real" objects - see here for guidance. 然后,您应该使用现有技术(例如JAXB)将XML数据转换为“真实”对象-请参阅此处以获得指导。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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