[英]Retrieve XML Element names with Java from unknown message format
我正在從許多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
}
我記錄的“已解析” XML如下所示:
#文本
行動
#文本
PARAMS
#文本
弄清楚了。 我僅在子節點上進行迭代,而不在父節點上進行迭代。 所以現在我只過濾掉#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的方法,那就太好了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.