java 解析String类型的xml

网络中有时候我们的参数是以xml类型传递的,有时会把xml拼成一个String字符串。

解析如下:

单一xml文档解析

xml文件

<?xml version="1.0" encoding="gb2312"?>

<IfResponse>

   <IfResult ></IfResult>

   <IfWarning ></IfWarning>

   <IfError >zh</IfError>

</IfResponse>

 

java 解析

public static boolean strParseXML(String str){
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
    DocumentBuilder builder; 
    String ifResult=null;
    String ifWarning=null;
 
     try    {  
       builder  =  factory.newDocumentBuilder();  
       Document doc  =  builder.parse( new  ByteArrayInputStream(str.getBytes()));
       if(doc.getElementsByTagName("IfResult").item(0).getFirstChild()!=null){
      ifResult=doc.getElementsByTagName("IfResult").item(0).getFirstChild().getNodeValue();
        if(ifResult.equals("0")){
        ……

         return true;
        }else{
         if(doc.getElementsByTagName("IfWarning").item(0).getFirstChild()!=null){
          ifWarning=doc.getElementsByTagName("IfWarning").item(0).getFirstChild().getNodeValue();
         }
         if(doc.getElementsByTagName("IfError").item(0).getFirstChild()!=null){
          ifError=doc.getElementsByTagName("IfError").item(0).getFirstChild().getNodeValue();
         }
         }
         
        }
       }
      
    }   catch  (ParserConfigurationException e)   {  
      e.printStackTrace();  
    }   catch  (SAXException e)   {  
      e.printStackTrace();  
    }   catch  (IOException e)   {   
      e.printStackTrace();  
    }
    return false;

  }

 

多重参数解析,以对象形式放到List里

 

 public static List<ExteriorImages> xmlInfoParaseModel(String strInfo){
  List<ExteriorImages> list=new ArrayList<ExteriorImages>();
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  
    DocumentBuilder builder;
    try{
     builder  =  factory.newDocumentBuilder();  
     Document doc  =  builder.parse( new  ByteArrayInputStream(strInfo.getBytes()));
     int nodeLength=doc.getElementsByTagName("message").getLength();//获取所有节点个数
     for(int i=0;i<nodeLength;i++){
      ExteriorImages images=new ExteriorImages();
      images.setR_code(doc.getElementsByTagName("code").item(i).getFirstChild().getNodeValue());
      images.setBar_state(doc.getElementsByTagName("state").item(i).getFirstChild().getNodeValue());
      images.setApp_user(doc.getElementsByTagName("user").item(i).getFirstChild().getNodeValue());

      list.add(images);
     }
     return list;
    
    }
       catch(ParserConfigurationException e)   {  
       e.printStackTrace();  
     }   catch(SAXException e)   { 
       e.printStackTrace();  
     }   catch(IOException e)   {
             e.printStackTrace();  
     } 
  return null;
 }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值