JAVA中调用XML

import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
 
public class code10_3{
 static Document document;
 public static void main(String[] args){
   if(args.length!=1){
      System.out.println("加载xml file");
      return;
   }
   DocumentBuilderFactory  dbf=DocumentBuilderFactory.newInstance();
   try{
     DocumentBuilder db=dbf.newDocumentBuilder();
     //读入XML文档//saxParser.parse(new InputSource("D.xml"),myHandler);
     document=db.parse(new File(args[0]));
     //获得根元素
     Node root=document.getDocumentElement();
     //获得根元素的子节点列表
     NodeList childs=root.getChildNodes();
     GetElement(childs);
   }catch(SAXException se){
     //解析过程错误
     Exception e=se;
     if(se.getException()!=null)
        e=se.getException();
        e.printStackTrace();
     }catch(ParserConfigurationException pe){
       //解析器设定错误
       pe.printStackTrace();
     }catch(IOException ie){
      //文件处理错误
      ie.printStackTrace();
     }
    }
    public static void GetElement(NodeList childs){
       int i=0;
       if(childs.getLength()==0)
         {//该节点没有子节点
          System.out.println("该节点没有子节点!");
         }
       for(i=0;i<childs.getLength();i++){
           //获取第i个子节点
          Node node=childs.item(i);
          //获取节点的类型,可以是ElementNode,TextNode,DocumentNode等
          short nodetype=node.getNodeType();
          /*ElementNode类型的节点可包含子节点和属性等*/
         if(nodetype==Node.ELEMENT_NODE)
          {
            //得到节点名称
            String name=node.getNodeName();
            String attrValue="",attrName="";
            System.out.println("this is element! name is:"+name);
            if(node.hasAttributes())
            {
              /*取出一个元素的属性,得到的是一个属性对象列表(NameNodeMap),
               *在此因为xml文档中元素只有一个属性,所以只取NameNodeMap中的第“0”个值。*/
              Node attrNode=node.getAttributes().item(0);
              /*取出该属性节点的Name和Value,即是一个ElementNode的属性名称和属性值*/
              attrName=attrNode.getNodeName();
              attrValue=attrNode.getNodeValue();
              System.out.println("this element attr is:"+attrValue+";attrnameis:"+attrName);
            }
            //如有子节点,递归调用GetElement()
            if(node.hasChildNodes())
             {GetElement(node.getChildNodes());}
          }
          /*Text类型节点没有子节点,节点名为#text,节点的值为xml文档中元素的值*/
         if(nodetype==Node.TEXT_NODE)
         {
          //该节点的name是"#text"
          String txtName=node.getNodeName();
          //取出Text类型节点的值
          Node thisparent=node.getParentNode();
          Node txtNode=thisparent.getChildNodes().item(0);
          String txtValue=txtNode.getNodeValue();
          if(txtValue.trim().length()>0)
            {
             System.out.println("txtName="+txtName+"; txtValue="+txtValue.trim());
            }
         }        
       }
      }
  }  
 
 

Java可以通过HTTP或SOAP协议调用XML接口。 1. HTTP调用XML接口 首先,需要准备好XML请求数据,然后使用Java的HttpURLConnection类发送HTTP POST请求,将XML数据作为请求体发送给XML接口: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class HttpXmlClient { public static void main(String[] args) { try { // 准备请求数据 String xml = "<request><param1>value1</param1><param2>value2</param2></request>"; // 发送HTTP POST请求 URL url = new URL("http://example.com/xmlapi"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/xml"); conn.setDoOutput(true); conn.getOutputStream().write(xml.getBytes()); // 获取响应数据 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; String line; while ((line = in.readLine()) != null) { response += line; } in.close(); // 处理响应数据 System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. SOAP调用XML接口 如果XML接口是基于SOAP协议实现的,可以使用Java的JAX-WS API调用: ```java import javax.xml.namespace.QName; import javax.xml.soap.*; import javax.xml.ws.Dispatch; import javax.xml.ws.Service; import java.net.URL; public class SoapXmlClient { public static void main(String[] args) { try { // 创建SOAP消息 MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope envelope = soapPart.getEnvelope(); SOAPBody body = envelope.getBody(); // 添加请求数据 QName qName = new QName("http://example.com/soapapi", "request"); SOAPElement request = body.addChildElement(qName); QName param1 = new QName("param1"); request.addChildElement(param1).addTextNode("value1"); QName param2 = new QName("param2"); request.addChildElement(param2).addTextNode("value2"); // 创建SOAP连接 URL url = new URL("http://example.com/soapapi?wsdl"); QName serviceName = new QName("http://example.com/soapapi", "Service"); QName portName = new QName("http://example.com/soapapi", "Port"); Service service = Service.create(url, serviceName); Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE); // 发送SOAP消息并接收响应 SOAPMessage response = dispatch.invoke(message); // 处理响应数据 SOAPPart responsePart = response.getSOAPPart(); SOAPEnvelope responseEnvelope = responsePart.getEnvelope(); SOAPBody responseBody = responseEnvelope.getBody(); String responseXml = responseBody.getFirstChild().toString(); System.out.println(responseXml); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上两种方法可以根据具体的XML接口实现进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值