这是xml
<a>
<b name="dataSource">
<property name="driverClass">oracle</property>
<property name="jdbcUrl">jdb:</property>
</b>
</a>
如何使用属性名称
获取标记中的值例如:oracle
<property name="driverClass">oracle</property>
使用标记名属性和属性值 driverClass
我想获得 oracle
答案 0 :(得分:1)
您可以使用XPath查询,例如/a/b/property[@name='driverClass']/text()
,它将返回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和How XPath Works了解更多详情
答案 1 :(得分:0)
试试这个:
XML输入:
< nodename attribute="value" > Something </ nodename>
Java代码:
NodesList subs = child.item(j).getChildNodes();
System.out.println(subs.item(0).getTextContent()); // >> Something