SAXReader reader = new SAXReader();
Document document = null; InputStream is; try { //讀入一個字符串使用的是utf-8的形式也就是說你的xml的格式也是utf-8的幺
is = new ByteArrayInputStream(textArea.getText() .getBytes("utf-8")); document = reader.read(is); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //獲取ns0:Verb的值并且輸出
Element rootElement = getDestElement(document, "Verb"); System.out.println(rootElement.getStringValue()); //getDestElement方法
// 使用dom4j獲取xml中element的值
public Element getDestElement(Document doc, String name) { HashMap xmlMap = new HashMap(); //ns0表示前綴,http://www./TC57/2008/schema/message代表其命名空間。
xmlMap.put("ns0", "http://www./TC57/2008/schema/message"); //使用xPath的方式查詢名稱為ns0:name的Element
XPath xpath = doc.createXPath("http://ns0:" + name); xpath.setNamespaceURIs(xmlMap); return (Element) xpath.selectSingleNode(doc); } 搞了兩天現在終于明白了,呵呵!僅供參考!
|
|