这里我有一些示例代码从Webservice获得响应。 我给出了这样的输入:
String values = Bham.getBDetails("xxxxxxxxx");
这里的肥皂用户界面响应看起来像:
<GetxxxxxhDetailsResponse >
<GetxxxxxhDetailsResult><![CDATA[<xxxxxFAMILY>
<FAMILYDETAIL>
<xxxx_ID>11111</2_ID>
<ID>50218036</ID>
<NAME>???? ????</NAME>
<FATHERNAME>????????</FATHERNAME>
</FAMILYDETAIL>
<FAMILYDETAIL>
<xxxx_ID>2222</2222_ID>
<ID>91622649</ID>
<NAME>????</NAME>
<FATHERNAME>?????</FATHERNAME>
</FAMILYDETAIL>
</xxxxxHFAMILY>]]>
</GetxxxxxhDetailsResult>
</GetxxxxxhDetailsResponse>
响应CDATA就是这样,我正在我的控制台中这样出来:
<xxxxFAMILY>
<FAMILYDETAIL>
<xxxxx_ID>9999-PXFR-00159</xxxxx_ID>
<ID>50218036</ID>
<NAME>???? ????</NAME>
<FATHERNAME>????????</FATHERNAME>
<DOB>01/01/1984</DOB>
<GENDER>?????</GENDER>
<MARITALSTATUS>???????</MARITALSTATUS>
<MOTHERNAME>????</MOTHERNAME>
<RELATIONSHIPWITHHOF>?????</RELATIONSHIPWITHHOF>
<SPOUSENAME>?????</SPOUSENAME>
</FAMILYDETAIL>
<FAMILYDETAIL>
<xxxxx_ID>9999-PXFR-00159</xxxxx_ID>
<ID>91622649</ID>
<NAME>????</NAME>
<FATHERNAME>?????</FATHERNAME>
<DOB>01/01/2007</DOB>
<GENDER>?????</GENDER>
<MARITALSTATUS>????????</MARITALSTATUS>
<MOTHERNAME>????</MOTHERNAME>
<RELATIONSHIPWITHHOF>??????</RELATIONSHIPWITHHOF>
<SPOUSENAME />
</FAMILYDETAIL>
</xxxxxFAMILY>
所以在这里我想得到xxxx_ID,ID所有属性。你能建议我吗?
答案 0 :(得分:1)
将XML读入文档,并使用Xpath或文档导航来获取您所追求的节点值。
Viral Patel有一个关于xpath和java的教程,但还有很多其他的。
http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/
从您发布的小内容中,您需要从详细信息实体中读取字符串并从中构建XML文档。阅读我发布的博客或此回复How to create a XML object from String in Java?
这应该让你去。
public static List<String> getIdFromXml(String xml) {
Document xmlDoc = loadXML(xml);
NodeList nodeList = xmlDoc.getElementsByTagName("ID");
List<String>ids = new ArrayList<String>(nodeList.getLength());
for(int i=0;i<nodeList.getLength(); i++) {
Node x = nodeList.item(i);
ids.add(x.getNodeValue());
}
return ids;
}
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}