如何使用java DOM解析器中的属性名称和标记名称获取标记中的值

时间:2015-07-22 06:24:52

标签: java dom xml-parsing

这是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

2 个答案:

答案 0 :(得分:1)

您可以使用XPath查询,例如/a/b/property[@name='driverClass']/text(),它将返回property节点的文本值,该节点的属性name等于driverClassb

的孩子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, xPathHow 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