如何从android中的xml标签获取特定值

时间:2015-10-12 09:02:18

标签: java android xml xml-parsing

<dict>
<key>Finance</key>
<dict>
<key>MainContent</key>
<array><string>Transactions</string><string>Booking Sales</string><string>Export Booking</string><string>Operation Revenue</string></array></dict>
<key>AboutUs</key>
<dict>
<key>MenuItems</key>
<array><dict><key>name</key><string>Ship Owning</string><key>submenu</key><array><string>Orient Express Lines FZCO</string><string>Transworld Bulk Carriers FZCO</string></array>
</dict>
<dict>
<key>name</key>
<string>Feeder</string>
<key>submenu</key>
<array><string>Orient Express Lines FZCO</string><string>Shreyas Shipping And Logistics Ltd</string></array>
</dict>
</dict>

在上面的xml文件中,如何获取<string>标记值。 有没有最有效的方法来获得价值。

1 个答案:

答案 0 :(得分:1)

如果你的xml没有很好地形成,你将不会走得太远。您可以使用JSoup等库来尝试清理xml。

见这里:http://try.jsoup.org/~qw0Vw1_TiKI71RmfxOn9HPL8u1U

然后只是使用该库来清理xml,并告诉它选择你想要的信息:

package doodle;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Main {

    public static void main(String[] args) {

        Document doc = Jsoup
                .parse("<dict><key>Finance</key><dict><key>MainContent</key><array><string>Transactions</string><string>Booking Sales</string><string>Export Booking</string><string>Operation Revenue</string></array></dict><key>AboutUs</key><dict><key>MenuItems</key><array><dict><key>name</key><string>Ship Owning</string><key>submenu</key><array><string>Orient Express Lines FZCO</string><string>Transworld Bulk Carriers FZCO</string></array></dict><dict><key>name</key><string>Feeder</string><key>submenu</key><array><string>Orient Express Lines FZCO</string><string>Shreyas Shipping And Logistics Ltd</string></array></dict></dict>");

        Elements elements = doc.select("string");

        for (Element element : elements) {
            System.out.println(element.text());
        }

    }

}

Transactions Booking Sales Export Booking Operation Revenue Ship Owning Orient Express Lines FZCO Transworld Bulk Carriers FZCO Feeder Orient Express Lines FZCO Shreyas Shipping And Logistics Ltd