当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How do I parse(and then find particular) XML data received from an API request?

问题描述:

I am almost a complete beginner regarding XML, as well as having only very basic knowledge about Java. I have tried looking up many things the past day and trying many code snippets but have not yet found a solution, so I don't know if my search terms are wrong, or I'm just too confused.

I have this URL(http://www.example.com/api/WebAPI/?dataset=wanted_dataset&keyref=12345) to get XML data from and it returns:

<channel>

<title>PSI Update</title>

<source>Airviro</source>

<item>

<region>...</region>

<region>...</region>

<region>...</region>

<region>

<id>rEA</id>

<latitude>1.35735</latitude>

<longitude>103.94000</longitude>

<record timestamp="20160210160000">

<reading type="NPSI" value="57"/>

<reading type="NPSI_PM25_3HR" value="56"/>

<reading type="NO2_1HR_MAX" value="5"/>

<reading type="PM10_24HR" value="32"/>

<reading type="PM25_24HR" value="18"/>

<reading type="SO2_24HR" value="4"/>

<reading type="CO_8HR_MAX" value="0.53"/>

<reading type="O3_8HR_MAX" value="31"/>

<reading type="NPSI_CO" value="5"/>

<reading type="NPSI_O3" value="13"/>

<reading type="NPSI_PM10" value="32"/>

<reading type="NPSI_PM25" value="57"/>

<reading type="NPSI_SO2" value="2"/>

</record>

</region>

<region>...</region>

<region>...</region>

And this is my code so far:

public class HazeCheck {

public void getHazeLevel() throws Exception{

URL myUrl = new URL("http://www.example.com/api/WebAPI/?dataset=wanted_dataset&keyref=12345");

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(myUrl.openStream());

XPathFactory xPathfactory = XPathFactory.newInstance();

XPath xpath = xPathfactory.newXPath();

XPathExpression expr = xpath.compile("I have no idea what I should put here");

String npsiValue = expr.evaluate(doc, XPathConstants.STRING).toString();

System.out.println("NPSI: " + npsiValue );

}

}

I'm trying to display the value inside [reading type="NPSI" value="57"] on the console.

I'm really sorry if any similar questions have been posted before, but I've looked through at least 20 different results but did not manage to understand or find a solution. It would be greatly appreciated if you could use idiot-proof explanations. Thank you in advance!

网友答案:

The w3c-specs are not always that easy to understand. A more simple explanation is to be found here Ten minute XPath tutorial

If you want to try your expression you can do it here: http://www.xpathtester.com/xpath

For example

/channel/item/region/record/reading[@type='NPSI_SO2']/@value

will give you 2 as a result.

分享给朋友:
您可能感兴趣的文章:
随机阅读: