Java Xpath查询
如何使用JavaXPath将第二个“c”标记d和f的值取为2Java Xpath查询,java,xml,xpath,tags,Java,Xml,Xpath,Tags,如何使用JavaXPath将第二个“c”标记d和f的值取为2 <a> <b> <c type="lol"> <d>1</d> <f>2</f> </c> <c type="lol"> <d>2</d> <f&g
<a>
<b>
<c type="lol">
<d>1</d>
<f>2</f>
</c>
<c type="lol">
<d>2</d>
<f>2</f>
</c>
<c type="h">
<d>v</d>
<f>d</f>
</c>
</b>
</a>
{
DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dB = dBFactory.newDocumentBuilder();
Document doc = dB.parse(url);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr=null;
String text= null;
expr= xpath.compile("//a/b/c[@type='lol']/d/text()");// this gets the first value
text = (String) expr.evaluate(doc, XPathConstants.STRING);
}
1.
2.
2.
2.
v
D
{
DocumentBuilderFactory dBFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dB=dBFactory.newDocumentBuilder();
文档doc=dB.parse(url);
System.out.println(“根元素:+doc.getDocumentElement().getNodeName());
XPathFactory=XPathFactory.newInstance();
XPath=factory.newXPath();
XPathExpression expr=null;
字符串文本=空;
expr=xpath.compile(//a/b/c[@type='lol']]/d/text()”;//这将获取第一个值
text=(String)expr.evaluate(doc,XPathConstants.String);
}
如何使用Java Xpath将第二个“c”标记d和f的值取为2使用:
//a/b/c[@type='lol'][2]/d/text()
谢谢,我自己也找到了解决办法。。刚才我是来添加我的解决方案的,u(@Kirill)已经提出了解决方案:)您的问题只需稍作调整即可-XML endtag是错误的,示例xpath显示的是“b”而不是d。下面的回答很好,不过,我今天学到了一些东西;]