2015-08-17 56 views
2

我從許多JMS消息傳遞主題解析XML,因此每個消息的結構變化很大,我想製作一個通用工具來解析它們。從未知消息格式中檢索帶有Java的XML元素名稱

開始,所有我想要做的就是元素名稱:

<gui-action> 
    <action>some action</action> 
    <params> 
    <param1>blue</param1> 
    <param2>tall</param2> 
    <params> 
</gui-action> 

我只是想找回字符串「鬼行動」,「行動」,「PARAMS」,「參數1」和「param2」。重複就好了。

我試過使用org.w3c.dom.Node,Element,NodeLists,我沒有太多的運氣。我不斷獲取元素值,而不是名稱。

private Element root; 
private Document doc; 
private NodeList nl; 

//messageStr is passed in elsewhere in the code 
//but is a string of the full XML message. 
doc = xmlParse(messageStr); 
root = doc.getDocumentElement(); 

nl = root.getChildNodes(); 
int size = nl.getLength(); 
for (int i=0; i<size; i++) { 
    log.info(nl.item(i).getNodeName()); 
} 





public Document xmlParse(String xml){ 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db; 
    InputSource is; 

    try { 
    //Using factory get an instance of document builder 
    db = dbf.newDocumentBuilder(); 
    is = new InputSource(new StringReader(xml)); 

    doc = db.parse(is); 

    } catch(ParserConfigurationException pce) { 
     pce.printStackTrace(); 
    } catch(SAXException se) { 
     se.printStackTrace(); 
    } catch(IOException ioe) { 
     ioe.printStackTrace(); 
    } 
    return doc; 
    //parse using builder to get DOM representation of the XML file 
} 

我登錄 「解析」 的XML看起來是這樣的:
#text
行動
#text
PARAMS
#text

回答

0

想通了。我只遍歷子節點,不包括父節點。所以現在我只是過濾出#texts,幷包含父項。 DERP。

 log.info(root.getNodeName()); 
     for (int i=0; i<size; i++) { 
      nodeName = nl.item(i).getNodeName(); 
      if(nodeName != "#text") { 
       log.info(nodeName); 
      } 
     } 

現在,如果有人知道一種方法來獲取整個文檔的NodeList,那就太棒了。

相關問題