[英]how to get the value in the tag using the attribute name and tag name in java DOM parser
this is the xml 这是XML
<a>
<b name="dataSource">
<property name="driverClass">oracle</property>
<property name="jdbcUrl">jdb:</property>
</b>
</a>
how to get the value in the tag using the attribute name 如何使用属性名称获取标签中的值
for example :oracle 例如:oracle
<property name="driverClass">oracle</property>
using tagname property and attribute value driverClass 使用标记名属性和属性值driverClass
i want to get oracle 我想得到甲骨文
You can use a XPath query, something like /a/b/property[@name='driverClass']/text()
which will return the text value of the property
node, which has an attribute name
equal to driverClass
and which is a of child b
, which is a child of a
您可以使用XPath查询,例如
/a/b/property[@name='driverClass']/text()
,它将返回property
节点的文本值,该property
节点的属性name
等于driverClass
,并且是孩子的b
,这是一个孩子a
For example... 例如...
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();
}
Which outputs oracle
哪个输出
oracle
Have a look at w3schools, xPath and How XPath Works for some more details 看一下w3schools,xPath和XPath的工作 原理 , 了解更多详细信息
Try this: 尝试这个:
XML input: XML输入:
< nodename attribute="value" > Something </ nodename>
Java code: Java代码:
NodesList subs = child.item(j).getChildNodes();
System.out.println(subs.item(0).getTextContent()); // >> Something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.