[英]get all node from xml having specific attriute value java
<main-project name="" version="1.0.2">
<data name="data">
<tag>
<link-to object="processor"/>
</tag>
</data>
<output name="output">
<tag>
<link-to object="processor"/>
</tag>
</output>
<processor name ="processor">
<tag>
<link-to object="data"/>
</tag>
</processor>
</main-project>
I wants to get all nodes having having attribute object = processor ,i have tried using 我想让所有具有属性对象=处理器的节点,我尝试使用
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList linkageNodesEpf = (NodeList) xPath.compile("//link-to[@object = 'processor']").evaluate(Doc, XPathConstants.NODESET);
This query gives empty list but when i replace link-to
to link
above query works fine and gives correct result,So i think may be dash(-) is creating the problem. 该查询给出了一个空列表,但是当我替换上面的查询的
link-to
link
可以正常工作并给出正确的结果时,所以我认为可能是dash(-)造成了问题。
please help me to solve this problem 请帮我解决这个问题
Well, that code: 好吧,该代码:
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class SimpleClass2 {
public static void main(String[] args) throws InterruptedException, XPathExpressionException, ParserConfigurationException, IOException, SAXException {
String str = "<main-project name=\"\" version=\"1.0.2\">\n" +
"<data name=\"data\">\n" +
"<tag>\n" +
"<link-to object=\"processor\"/>\n" +
"</tag>\n" +
"</data>\n" +
"<output name=\"output\">\n" +
"<tag>\n" +
"<link-to object=\"processor\"/>\n" +
"</tag>\n" +
"</output>\n" +
"<processor name =\"processor\">\n" +
"<tag>\n" +
"<link-to object=\"data\"/>\n" +
"</tag>\n" +
"</processor>\n" +
"</main-project>";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document xmlDoc = builder.parse(new ByteArrayInputStream(str.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList linkageNodesEpf = (NodeList) xPath.compile("//link-to[@object = 'processor']").evaluate(xmlDoc, XPathConstants.NODESET);
for (int i = 0; i < linkageNodesEpf.getLength(); i++) {
System.out.println(linkageNodesEpf.item(i));
}
}
}
Produces sush results on my machine(oracle jdk8_45): 在我的机器上产生sush结果(oracle jdk8_45):
[link-to: null]
[link-to: null]
Could you try copying it, what results does it produce? 您可以尝试复制它吗,它会产生什么结果?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.