如何从xml soap响应中检索元素

时间:2015-06-22 16:07:39

标签: xml xpath

下面是我的xml文件格式(soap响应),我想检索每个属性并在jsp中显示?

 <?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0" class="java.beans.XMLDecoder">
 <object class="com.vcompack.XRSTService.MashProfile">



        <void property="build">
       <string>5-6-8</string>
      </void>
      <void property="careof">
       <string> Mariya</string>
      </void>
      <void property="dist">
       <string>7</string>
      </void>
      <void property="name">
       <string>GUNTUR</string>
      </void>
      <void property="dob">
       <string>01/01/1976</string>
      </void>
      <void property="vid">
       <string>1001100</string>
      </void>
      <void property="gender">
       <string>F</string>
      </void>
      <void property="mandal">
       <string>32</string>
      </void>
      <void property="m_name">
       <string>TENALI</string>
      </void>
      <void property="name">
       <string>Ponjamma</string>
      </void>
      <void property="phoneNo">
       <string>101</string>
      </void>
      <void property="pincode">
       <string>522201</string>
      </void>
      <void property="swstxn">
       <string>WS-TXN:20150622092733878</string>
      </void>
      <void property="scode">
       <string>1</string>
      </void>
      <void property="status">
       <string>100</string>
      </void>
      <void property="street">
       <string>Vari Street</string>
      </void>
      <void property="uid">
       <string>6524588</string>
      </void>
      <void property="village">
       <string>12</string>
      </void>
      <void property="village_name">
       <string>Tena</string>
      </void>
     </object>
    </java>

我尝试了各种各样的方法,将大量的jar放在lib中,但没有提供解决方案。很多人建议使用xpath.Could有人帮我检索JAVA中的所有属性吗?

1 个答案:

答案 0 :(得分:0)

以下路径表达式返回名为property

的所有属性
//@property

在java中,您可以使用以下代码:

     XPath xpath = XPathFactory.newInstance().newXPath();
        String expression1 = "//@property";
        String expression2 = "//void/string";
        InputSource inputSource = new InputSource("soapMessage.xml");
        NodeList nodes1 = (NodeList) xpath.evaluate(expression1, inputSource, XPathConstants.NODESET);
        NodeList nodes2 = (NodeList) xpath.evaluate(expression2, inputSource, XPathConstants.NODESET);
        for (int i = 0; i < nodes1.getLength(); i++) {
            Attr attr = (Attr) nodes1.item(i);
            Element element = (Element) nodes2.item(i);
            String output = attr.getNodeValue()+'-'+element.getTextContent();
            System.out.println(output);
}