Anthony J
Anthony J

Reputation: 581

How to get an attribute within an Element ID

I have the following XML data. I would like to get the lat & lng values that only pertain to the location, not the southwest. How can I do this without having to also read the southwest.

 `<geometry>
   <location>
    <lat>51.5739894</lat>
    <lng>-0.1499698</lng>
   </location>
    <southwest>
     <lat>51.5727314</lat>
     <lng>-0.1511809</lng>
    </southwest>
</geometry>`

So far, I've tried: `

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes){
        if(localName.equals("location")){
            Node n1 = new Node(
                    Double.parseDouble(attributes.getValue("lat"))
                    Double.parseDouble(attributes.getValue("lng"))
            );
            current = n1;
        }
    }`

Upvotes: 0

Views: 34

Answers (2)

SomeDude
SomeDude

Reputation: 14238

If your xml is not huge, its ok if you use an approach using XPathFactory. Otherwise go for SAX parser. But you need to do extra processing when writing SAX parsers particularly when you ahve conditions like I want only location's lat value.

I would use an xpath approach, very simple to use, no need to use third party. It can be done via java.xml.*

Code would be :

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( new File( ".//input.xml" ) );

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();

XPathExpression latExpr = xpath.compile( "//location/lat" );
XPathExpression lngExpr = xpath.compile( "//location/lng" );

Object exprEval = latExpr.evaluate( doc, XPathConstants.NUMBER );
if ( exprEval != null )
{
    System.out.println( "Location's lat value is :" + exprEval );
}
exprEval = lngExpr.evaluate( doc, XPathConstants.NUMBER );
if ( exprEval != null )  
{
   System.out.println( "Location's lng value is :" + exprEval );
}

input.xml contains your xml. It uses the xpath : //location/lat which means get me the value of lat whose parent is location. And evaluate the xpath as a NUMBER.

Output is :

Location's lat value is :51.5739894
Location's lng value is :-0.1499698

Upvotes: 2

Saorikido
Saorikido

Reputation: 2290

For this particular case, if I were you I'll use org.json parse as JSONObject to query every node.

JSONObject jsonObject = XML.toJSONObject(xml).getJSONObject("geometry").getJSONObject("location");
String lat = jsonObject.getString("lat");
String lng = jsonObject.getString("lng");

Upvotes: 1

Related Questions