自己随便用遍历的方法来取第一个在xml文件中出现的某节点的值的方法1,能满足一些需求。不过有时候需要指定节点的全路径,于是又写了个方法来做,不过发现若xml文件中存在命名空间则取不到值,就自己整理了方法2,在此备份:
方法1:
public static String getNoteValue(String xml_str,File file,String note_name){
String result="";
try {
Document doc = null;
if(xml_str!=null&&!"".equals(xml_str)){
doc=getXmlDoc(xml_str);//用SAXReader获取,此处略
}else if(file!=null){
doc = getXmlDoc(file);
}
if(doc==null)
return result;
Element root = doc.getRootElement();
Iterator iter=root.elementIterator();
List ls=new ArrayList();
if(iter!=null)
{
while(iter.hasNext())
{
Element element = (Element)iter.next();
String e_name=element.getName();
String e_value=element.getText();
if(note_name.equals(e_name)){
result=e_value;
break;
}else if(element.elementIterator()!=null)
ls.add(element);
}
if(result.length()==0)
result=getFinalString(ls,note_name);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return result;
}
方法2:
public static String getExactNoteValue(String xml_str,File file,String node_path){
if((xml_str==null||"".equals(xml_str.trim()))&&file==null)
return "";
String result="";
try {
Document doc = null;
if(xml_str!=null&&!"".equals(xml_str)){
doc=getXmlDoc(xml_str);
}else if(file!=null){
doc = getXmlDoc(file);
}
Element root=doc.getRootElement();
String nps=root.getNamespace().getText();
if(nps!=null&&!"".equals(nps)){
Map map = new HashMap();
map.put("xmlns",nps);
if(node_path.startsWith("/")){
node_path=node_path.replaceAll("/","/xmlns:");
}else{
node_path="/xmlns:"+node_path.replaceAll("/","/xmlns:");
}
XPath xp=doc.createXPath(node_path);
xp.setNamespaceURIs(map);
Node nn=xp.selectSingleNode(doc);
if(nn!=null)
{
result=nn.getText();
}
}else{
Node node=doc.selectSingleNode(node_path);
if(node!=null&&node.hasContent()){
result=node.getText();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}