2012-07-28 77 views
2

我有个国家的XML列表如下:为什么xpath选择空格?

<countries> 
    <country> 
    <code>CA</code> 
    <country>Canada</country> 
    </country> 
    ... etc... 
</countries> 

我要选择的节点,并在它们之间迭代所以使用

path "/countries/*" 

,然后在JavaScript:

nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null); 

当我迭代时,我发现第一个和第三个节点是空白(换行符),第二个和第四个节点是我想要的实际XML。

如何使用XPath忽略空白节点?我只对XML部分感兴趣,并且我不能保证XML将包含换行符。

+0

为什么你就不能使用'// country'? – Raffaele 2012-07-28 12:02:50

+0

这将如何工作?这是一个“国家”的名单。 – sproketboy 2012-07-28 12:21:03

+0

对不起,我错误地把Java放在那里。这是使用JavaScript的客户端。 – sproketboy 2012-07-28 12:22:09

回答

0

难道你不能用这样简单的程序吗?

NodeList countries = (NodeList) xpath.evaluate("//countries/country", 
    builder.parse(inputStream), 
    XPathConstants.NODESET); 

for (int i = 0; i < countries.getLength(); i++) { 
    Node country = notes.item(i); 
    String code = (String) xpath.evaluate("./code/text()", country, 
     XPathConstants.STRING); 
    String name = (String) xpath.evaluate("./country/text()", country, 
     XPathConstants.STRING); 

    System.out.println(String.format("%s has country code %s", name, code)); 
} 

与输入

<countries> 
    <country> 
    <code>CA</code> 
    <country>Canada</country> 
    </country> 
    <country> 
    <code>FR</code> 
    <country>France</country> 
    </country> 
    <country> 
    <code>IT</code> 
    <country>Italy</country> 
    </country> 
    <country> 
    <code>US</code> 
    <country>United States</country> 
    </country> 
</countries> 

输出

Canada has country code CA 
France has country code FR 
Italy has country code IT 
United States has country code US 
+0

是的,虽然是Java。我需要使用JavaScript在客户端上执行此操作。我只是试图不选择行提要作为节点。 – sproketboy 2012-07-28 12:20:12

+0

你可以很容易地翻译成Javascript。请记住,如果您选择// countries/*,您将获得所有子节点,包括dom元素和文本节点(您提到的提要)。如果您对顶级国家/地区元素感兴趣,则无法理解//国家/国家/地区出现的问题。 – Raffaele 2012-07-28 12:33:04

+0

是的,谢谢。你是对的。选择*包含空白,但如果我只是按照您指定的名称选择节点,那么它工作正常。谢谢。 – sproketboy 2012-07-28 13:07:27