简体   繁体   中英

Get text from tag with attribute jsoup

Im trying get the text from a tag "Data" with name="telefono" but I can't solve it:

<Placemark>
    <name>Iglesia </name>
    <description> Abril </description>

    <ExtendedData>
        <Data name='description'>
            <value>4444</Data>
        <Data name='phone'>
            <value>5555</value>
        </Data>
    </ExtendedData>
    <Point>
        <coordinates>-0.5191416,38.9848326,0.0</coordinates>
    </Point>
</Placemark>

I have a "for" that select all placemark:

for(org.jsoup.nodes.Element i : e.select("Placemark"))

I have tried all possibilities to get the value of the the phone 5555

but I don't know it, always get all data phone and description.

System.out.println((i.select("ExtendedData").text()));
System.out.println((i.select("ExtendedData").select("Data").tagName("phone").text()));
System.out.println("(i.select("ExtendedData").tagName("phone").text()));

If you want to get only 5555 then you can use text() of <Data name='phone'> . If there can be more of such elements then you may need to add more data about its ancestors/parents but for example you posted this should be enough:

System.out.println(doc.select("data[name=phone]").text());

System.out.println((i.select("ExtendedData").select("Data").tagName("phone").text()));

The above code doesn't work because the tagName method will update the tag name of all selected Data elements. Let's say the below element is selected:

<Data name='phone'><value>5555</value></Data>

Calling the tagName method would turn it into:

<phone name='phone'><value>5555</value></phone>

Instead try this:

System.out.println( i.select("ExtendedData > Data[name=phone]").text() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM