使用Java从未知消息格式检索XML元素名称

使用Java从未知消息格式检索XML元素名称,java,xml,Java,Xml,我正在解析来自许多JMS消息传递主题的XML,因此每条消息的结构变化很大,我想制作一个通用工具来解析它们 首先,我要做的就是获取元素名称: <gui-action> <action>some action</action> <params> <param1>blue</param1> <param2>tall</param2> <params> </gui

我正在解析来自许多JMS消息传递主题的XML,因此每条消息的结构变化很大,我想制作一个通用工具来解析它们

首先,我要做的就是获取元素名称:

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

一些行动
蓝色
高的
我只想检索字符串“gui action”、“action”、“params”、“param1”和“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
}
私有元素根;
私人文件文件;
私有节点列表nl;
//messageStr在代码中的其他位置传递
//但它是完整XML消息的字符串。
doc=xmlParse(messageStr);
root=doc.getDocumentElement();
nl=root.getChildNodes();
int size=nl.getLength();

对于(int i=0;i来说,我找到了答案。我只在子节点上迭代,不包括父节点。所以现在我只过滤掉#文本,并包括parent.Derp

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