从java中的xml链接中提取URL位置

问题描述 投票:-1回答:1

我是java的新手,我有一个链接“https://moz.com/blog-sitemap.xml”,它有URL,我想得到它们并将它们保存在字符串向量/数组中。

我先尝试了这个,看看我将如何获得链接

URL robotFile = new URL("https://moz.com/blog-sitemap.xml");

    //read robot.txt line by line
    Scanner robotScanner = new Scanner(robotFile.openStream());
    while (robotScanner.hasNextLine()) {
        System.out.println(robotScanner.nextLine());
    }

这是示例输出enter image description here

我的答案是,是否有一种简单的方法来获取这些链接,而不是在每一行上循环检查它是否包含“https”所以我可以从中提取链接?

java xml sitemap
1个回答
-1
投票

您可以使用Jsoup更轻松地执行此操作:

    List<String> urlList = new ArrayList<>();
    Document doc = Jsoup.connect("https://moz.com/blog-sitemap.xml").get();
    Elements urls = doc.getElementsByTag("loc");

    for (Element url : urls) {
        urlList.add(url.text());
    }
© www.soinside.com 2019 - 2024. All rights reserved.