我正在尝试从我的 XML 数据文件(例如 Pantone 100)打印特定节点。我希望它打印出 pantone 100 中的所有属性,例如所有颜色和它们保存的数据,但我不确定如何格式化 XPath 以仅提取特定 pantone 编号的方式正确编译寻找。
编辑:下面的代码输出空值
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());
}
}
}
输出 空
最佳答案
我不是 xpath 专家(今天才真正了解它)所以我不是 100% 确定这一点,但你有 /inventory/product/pantone/text(@=100)
,而是试试这个:
/inventory/Product[@pantone='100']
据我了解,这将匹配 Product
具有属性 pantone
等于 "100"
.
至于打印数据,我不确定,但希望这会让您走上正轨。
Edit: Check out this page:
Node
. It is the javadoc for theNode
type. As geert3 said in his/her answergetNodeValue()
returns the value of the node, which in this case is the value of the element, not the attributes (for example: in<element>value</element>
the value of the element element is value) which in your case isnull
because it's empty (if it thought the type was String maybe it would be""
instead ofnull
?).Try calling
Node#getAttributes()
and then iterating across theNamedNodeMap
withNamedNodeMap#item(int)
to get theNode
s. These should be the attributes (I think, if I am understanding the API correctly).getNodeName()
should be the name of the attribute (e.g.,pantone
) andgetNodeValue()
should be the value of the attribute (e.g.,100
).
关于Java XPath 表达式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31547431/