这是我使用 java 的第一天,我尝试为我的网站构建一个小的 xml 解析器,这样我就可以清楚地查看我的 sitemaps.xml 。我使用的代码是这样的
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.util.List;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
class downloadxml {
public static void main(String[] args) throws IOException {
String str = "http://www.someurl.info/sitemap.xml";
URL url = new URL(str);
InputStream is = url.openStream();
int ptr = 0;
StringBuilder builder = new StringBuilder();
while ((ptr = is.read()) != -1) {
builder.append((char) ptr);
}
String xml = builder.toString();
org.jdom2.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
org.jdom2.Document doc = saxBuilder.build(new StringReader(xml));
System.out.println(xml);
Element xmlfile = doc.getRootElement();
System.out.println("ROOT -->"+xmlfile);
List list = xmlfile.getChildren("url");
System.out.println("LIST -->"+list);
} catch (JDOMException e) {
// handle JDOMExceptio n
} catch (IOException e) {
// handle IOException
}
System.out.println("===========================");
}
}
当代码通过时
System.out.println(xml);
我得到了 xml 站点地图的清晰打印。当涉及到:
System.out.println("ROOT -->"+xmlfile);
输出:
ROOT -->[Element: <urlset [Namespace: http://www.sitemaps.org/schemas/sitemap/0.9]/>]
它还会找到根元素。但是由于某种原因,当脚本应该用于 child 时,它返回一个空打印:
System.out.println("LIST -->"+list);
输出:
LIST -->[]
换个方式应该怎么办?任何获得 child 的指示?
XML 看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>http://www.image.url</loc>
<image:image>
<image:loc>http://www.image.url/image.jpg</image:loc>
</image:image>
<changefreq>daily</changefreq>
</url>
<url>
</urlset>
最佳答案
您在一天内走了很长一段路。
简而言之,您忽略了 XML 文档的命名空间。更改行:
List list = xmlfile.getChildren("url");
到
Namespace ns = Namespace.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9");
List list = xmlfile.getChildren("url", ns);
为了您的方便,您可能还想将整个构建过程简化为:
org.jdom2.Document doc = saxBuilder.build("http://www.someurl.info/sitemap.xml");
关于Java jdom xml解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16848244/