有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

带变量的Java Xpath

我有一个XML:

<rdf:RDF 
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://purl.org/rss/1.0/">
<channel rdf:about="http://www.web.com/news.rss">
<items>
<rdf:Seq>
    <rdf:li resource="http://www.web.com/news1" />
    <rdf:li resource="http://www.web.com/news2" />
 </rdf:Seq>
</items>
</channel>
<item rdf:about="http://www.web.com/news1">
<title>my title</title>
<link>http://www.web.com/news1.html</link>
<description> bla bla </description>
</item>
<item rdf:about="http://www.web.com/news2">
<title>My Title 2</title>
<link>http://www.web.com/news2.html</link>
<description> bla bla 2 </description>
</item>
</rdf:RDF>

下面是我的代码,可以尝试打印每个rdf:li的标题

public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(System.out, true, "Cp850")); 
    XPath xPath =  XPathFactory.newInstance().newXPath();
   DocumentBuilderFactory factory = 
    DocumentBuilderFactory.newInstance();
   DocumentBuilder parser = factory.newDocumentBuilder();
   Document doc = parser.parse(args[0]);

   Element racine = doc.getDocumentElement(); 
       System.out.println("racine: "+ racine);
   NodeList nl = racine.getElementsByTagName("rdf:li");
for (int k = 0; k < nl.getLength(); ++k) {
    Element e = (Element) nl.item(k);
    String NewsTitle = e.getAttribute("resource");
         System.out.println("from :" + NewsTitle);
     String NoTitre = xPath.compile("//item[@rdf:about='" + NewsTitle + "']/title").evaluate(doc);
              System.out.println("Title : "+ NoTitre );

    }
}

在我的循环中一切正常,我的NewsTitle变量给了我很好的结果

我的问题是xpath。Compile不好,我需要帮助知道如何调用我的xpath来查找每个新闻的标题,这些新闻将给出以下结果:

发件人:http://www.web.com/news1
标题:bla bla
发件人:http://www.web.com/news2
标题:bla bla 2

我不能用粗体字写这句话。(标题:布拉布拉)

谢谢


共 (1) 个答案

  1. # 1 楼答案

    谢谢我终于找到了自己。 Xpath需要删除名称空间rdf: 给这个:

    String NoTitre = xPath.compile("//item[@about='" + NouvelleTitre + "']/title").evaluate(doc);