2015-07-21 88 views
1

我试图从我的XML数据文件(例如Pantone 100)打印特定节点。我希望它能够打印出pantone 100的所有属性,例如所有的颜色和数据,但我不确定如何正确地格式化XPath编译的方式,以便只取得特定的pantone编号。我是寻找。Java XPath表达式错误

编辑:下面输出的代码空

XML数据

<inventory> 
    <Product pantone="100" blue="7.4" red="35" green="24"> </Product> 
    <Product pantone="101" blue="5.4" red="3" rubine="35" purple="24"> </Product> 
    <Product pantone="102" orange="5.4" purple="35" white="24"> </Product> 
    <Product pantone="103" orange="5.4" purple="35" white="24"> </Product> 
    <Product pantone="104" orange="5.4" purple="35" white="24"> </Product> 
    <Product pantone="105" orange="5.4" purple="35" white="24"> </Product> 
    <Product pantone="106" black="5.4" rubine="35" white="24" purple="35" orange="5.4"> </Product> 
</inventory> 

代码

import org.w3c.dom.*; 
import javax.xml.xpath.*; 
import javax.xml.parsers.*; 
import java.io.IOException; 
import org.xml.sax.SAXException; 

public class XPathDemo { 

    public static void main(String[] args) 
      throws ParserConfigurationException, SAXException, 
      IOException, XPathExpressionException { 

     DocumentBuilderFactory domFactory 
       = DocumentBuilderFactory.newInstance(); 
     domFactory.setNamespaceAware(true); 
     DocumentBuilder builder = domFactory.newDocumentBuilder(); 
     Document doc = builder.parse("data.xml"); 
     XPath xpath = XPathFactory.newInstance().newXPath(); 
     // XPath Query for showing all nodes value 
     XPathExpression expr = xpath.compile("/inventory/Product[@pantone='100']"); 

     Object result = expr.evaluate(doc, XPathConstants.NODESET); 
     NodeList nodes = (NodeList) result; 
     for (int i = 0; i < nodes.getLength(); i++) { 
      System.out.println(nodes.item(i).getNodeValue()); 
     } 
    } 
} 

输出 空

回答

2

输出为空,因为getNodeValue在这里不适用。 getTextContent会为您提供开始和结束标记之间的文本,例如FOOBAR在这个例子:

<Product pantone="100" blue="7.4" red="35" green="24">FOOBAR</Product>`. 

但是,如果你想打印的所有属性值的结果集:

NodeList nodes = (NodeList)result; 
    for (int i = 0; i < nodes.getLength(); i++) 
    { 
     NamedNodeMap a = nodes.item(i).getAttributes(); 
     for (int j=0; j<a.getLength(); j++) 
      System.out.println(a.item(j)); 
    } 

或使用a.item(j).getNodeName()a.item(j).getNodeValue()分别检索属性名称或值。

3

我使用XPath(字面上今天学到它)没有专家,所以我不是100%肯定这一点,但你必须/inventory/product/pantone/text(@=100),而是试试这个:

/inventory/Product[@pantone='100'] 

据我了解,这将匹配Product,属性为pantone,等于"100"

至于打印数据,我不确定,但希望这会让你走上正轨。

编辑:查看此页面:Node。它是Node类型的javadoc。由于geert3在他/她的回答中说getNodeValue()返回节点的值,在这种情况下该值是元素的值,而不是属性(例如:在<element>value</element>中元素元素的值是值),在您的情况下null因为它是空的(如果它认为类型是字符串,也许它会是""而不是null?)。

尝试呼叫Node#getAttributes(),然后在NamedNodeMapNamedNodeMap#item(int)之间迭代以获得Node这些应该是属性(我认为,如果我正确理解API)。 getNodeName()应该是属性的名称(例如,pantone)并且getNodeValue()应该是该属性的值(例如,100)。

+0

这似乎工作,但我得到“空”作为输出。不知道什么是错的 – ssj3goku878

+1

@ ssj3goku878我已经在Google上搜索了'Node' javadoc,并尽了我最大的努力来更新答案,成为您正在寻找的东西。尝试一下并回报。 –