[英]how to get the value in the tag using the attribute name and tag name in java DOM parser
这是XML
<a>
<b name="dataSource">
<property name="driverClass">oracle</property>
<property name="jdbcUrl">jdb:</property>
</b>
</a>
如何使用属性名称获取标签中的值
例如:oracle
<property name="driverClass">oracle</property>
使用标记名属性和属性值driverClass
我想得到甲骨文
您可以使用XPath查询,例如/a/b/property[@name='driverClass']/text()
,它将返回property
节点的文本值,该property
节点的属性name
等于driverClass
,并且是孩子的b
,这是一个孩子a
例如...
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(JavaApplication244.class.getResourceAsStream("/Test.xml"));
XPathFactory xf = XPathFactory.newInstance();
XPath xPath = xf.newXPath();
XPathExpression expression = xPath.compile("/a/b/property[@name='driverClass']/text()");
String value = expression.evaluate(doc);
System.out.println(value);
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException exp) {
exp.printStackTrace();
}
哪个输出oracle
看一下w3schools,xPath和XPath的工作 原理 , 了解更多详细信息
尝试这个:
XML输入:
< nodename attribute="value" > Something </ nodename>
Java代码:
NodesList subs = child.item(j).getChildNodes();
System.out.println(subs.item(0).getTextContent()); // >> Something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.