как читать XML в Java? - PullRequest
       1

как читать XML в Java?

0 голосов
/ 19 октября 2011

у меня есть следующий xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root> 
<processid>processid_1111</processid>
<suggestion>
       <geo1>a</geo1>
       <geo2>b</geo2>
       <geo3>c</geo3>
       <standarddatasuggestion>account1</standarddatasuggestion>
</suggestion>
<suggestion>
      <geo1>d</geo1>
      <geo2>e</geo2>
      <geo3>f</geo3>
      <geo4>g</geo4>
      <standarddatasuggestion>account2</standarddatasuggestion>
</suggestion>
<taskid>taskid_111</taskid>
</root>

Я хочу разработать метод, который может принимать имя узла и на основе имени узла возвращать соответствующий узел и его значение в объектах карты. Пожалуйста, помогите мне разобраться с вышеуказанной проблемой.

Я попробовал:

public SortedMap[] getObjectValueFromXML(Object xmlObject) 
  {
    Node item = null;
    SortedMap[] map = null;
    String subchildnodeName = null;
    String subchildnodeValue = null;
    Map subchildmap[] = null;
    try {
        if (xmlObject == null) {
            throw new NullPointerException("XML object found null");
        }

        factory = DocumentBuilderFactory.newInstance();
        builder = factory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(xmlObject.toString().getBytes()));
        doc.getDocumentElement().normalize();
        node = doc.getDocumentElement();
        root = node.getNodeName();
        nList = doc.getElementsByTagName(root);

        for (int temp = 0; temp < nList.getLength(); temp++) {
            nNode = nList.item(temp);
            NodeList childNodes = nNode.getChildNodes();
            int length = childNodes.getLength();
            map = new TreeMap[length];

            String nodeValues[][] = new String[length][2];
            for (int i = 0; i < length; i++) {

                item = nNode.getChildNodes().item(i);
                String parentnodeName = item.getNodeName();
                int noderepetationlength = doc.getElementsByTagName(parentnodeName).getLength();
                // System.out.println(noderepetationlength);
                NodeList rootchildNodes = item.getChildNodes();
                String parentnodeValue = rootchildNodes.item(0).getNodeValue();
                map[i] = new TreeMap();
                if (parentnodeName != null && parentnodeValue != null && noderepetationlength <= 1) {
                    map[i].put(parentnodeName, parentnodeValue);
                } else 
                {
                    subchildmap = new HashMap[noderepetationlength];
                    for (int t = 0; t < noderepetationlength; t++) 
                    {

                        NodeList childNodes1 = item.getChildNodes();
                        int length1 = childNodes1.getLength();
                         subchildmap[t] = new HashMap(); 
                        for (int j = 0; j < length1; j++) 
                        {

                            Node item2 = childNodes1.item(j);
                            if (item2.getNodeType() == Node.ELEMENT_NODE) 
                            {
                                subchildnodeName = item2.getNodeName();
                                NodeList childNodes2 = item2.getChildNodes();
                                int length2 = childNodes2.getLength();
                                for (int k = 0; k < length2; k++) 
                                    subchildnodeValue = childNodes2.item(k).getNodeValue();

                            }
                            subchildmap[t].put(subchildnodeName, subchildnodeValue);

                        }
                        map[i].put(parentnodeName, subchildmap[t]);
                    }
                }
            }//else
        } //end of for-loop

    } catch (ParserConfigurationException pce) {
    } catch (NullPointerException nofe) {
    } catch (SAXException saxException) {
    } catch (IOException ioe) {
    }

    return map;
} 

, но не удалось получить ожидаемый результат.

Спасибо

Ответы [ 4 ]

2 голосов
/ 19 октября 2011

Jaxb хорошо послужил мне в прошлом, но может быть излишним для этой ситуации.

Информация здесь

0 голосов
/ 19 октября 2011

http://java.sun.com/developer/Books/xmljava/ch03.pdf

http://www.exampledepot.com/taxonomy/term/374

String[] FindNodeValues(String XMLString,String nodeName,String[] vals)
{
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse(XMLString);//XML String should contain the XML
Node node = doc.getDocumentElement();
NodeList list =doc.getElementsByTagName(nodeName).item(0).getChildNodes();
for(i=0;i<list.length;i++){vals[i]=list.item(0).getNodeValue();}
return vals;
}

Считайте, что это только псевдокод. Возможно, есть ошибки;

0 голосов
/ 19 октября 2011

Я считаю, что это отличный учебник:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

0 голосов
/ 19 октября 2011

Вы можете использовать SAX и DOM API анализатора.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...