dom4j解决中文问题及获得xml中元素的值的例子

来源:百度文库 编辑:神马文学网 时间:2024/04/27 17:43:05
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.iec.ch/TC57/2008/schema/message代表其命名空间。
  xmlMap.put("ns0", "http://www.iec.ch/TC57/2008/schema/message"); //使用xPath的方式查询名称为ns0:name的Element
  XPath xpath = doc.createXPath("//ns0:" + name);
  xpath.setNamespaceURIs(xmlMap);
  return (Element) xpath.selectSingleNode(doc);
 }  搞了两天现在终于明白了,呵呵!仅供参考!