java - 无法使用Java读取XML文档

标签 java xml-parsing

我正在尝试解析一个 XML 文件:网络上的站点地图。我尝试了很多组合但没有成功。我确信我已经很接近了,但我没有发现任何有用的东西......

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
org.w3c.dom.Document doc = factory.newDocumentBuilder().parse(new URL("https://www.lavisducagou.nc/page-sitemap.xml").openStream());
System.out.println("XML = " + doc);

输出:

XML = [#document: null]

为什么输出是[#document: null]

文档

("https://www.lavisducagou.nc/page-sitemap.xml)

确实在线。

预先感谢您的帮助。

最佳答案

您看到的只是 com.sun.org.apache.xerces.internal.dom.DocumentImpl 的 toString 实现

public String toString() {
    return "["+getNodeName()+": "+getNodeValue()+"]";
}

由于文档没有节点值,因此它为空。您需要做的是获取子节点并迭代并获取所需的详细信息。

由于防火墙问题,我无法使用 java 访问该 URL,但这是同一文件本身的一小段摘录。

<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl"  href="//www.lavisducagou.nc/wp-content/plugins/wordpress-seo/css/main-sitemap.xsl"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://www.lavisducagou.nc/</loc>
    <lastmod>2018-07-14T11:30:25+11:00</lastmod>
  </url>
  <url>
    <loc>https://www.lavisducagou.nc/sinscrire/</loc>
    <lastmod>2018-05-03T16:58:35+11:00</lastmod>
  </url>
</urlset>

刚刚通过后续步骤更新了您的代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
org.w3c.dom.Document doc = factory.newDocumentBuilder().parse(new URL("https://www.lavisducagou.nc/page-sitemap.xml").openStream());
System.out.println("XML = " + doc);
NodeList nodeList = doc.getChildNodes();
for (int i=0; i<nodeList.getLength();i++) {
   System.out.println(nodeList.item(i).getNodeName());
}

示例输出:

XML = [#document: null]
xml-stylesheet
urlset

关于java - 无法使用Java读取XML文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069877/

相关文章:

java - 如何通过减去 2 个 nanoTime 对象获得有意义的结果?

java - 使用继承和多态来解决一个常见的游戏问题

java - 使用搜索 View 时适配器未更新

Java 程序导致 Matlab 崩溃

python - Youtube-dl 订阅 mp3

java - 无法在具有 <DOCTYPE> 标记的 XML 文件中从 JAVA 运行 Xpath 查询

java - 从xls/xlsx文档中读取,哪个API? java

python - 使用 xmltodict 从已解析的 xml 文件的键中删除特殊字符

java - 捕获异常后的xml解析和验证

java - Nodelist.item 返回 null