![](/img/trans.png)
[英]how to get the value in the tag using the attribute name and tag name in java DOM parser
[英]How get tag value using DOM parser
我在应用程序中使用dom解析器。 所以。 我有下一种情况:
XML:
<test>
<A>
<B>hello</B>
world
</A>
</test>
码:
private TagA parseTagA(Node node) {
TagA tagA = new TagA();
if (node.hasChildNodes()) {
NodeList childList = node.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
// gets child
Node child = childList.item(i);
// parse <B> tag
if (child != null && "B".equals(child.getNodeName())) {
tagA.setTagB(parseTagB(child));
}
}
}
String tagABody = node.getTextContent();
tagA.setBody(tagABody);
return tagA;
}
我使用node.getTextContent()方法获取标签A的值,但我也获取标签B的值。 我的意思是“ tagABody”的值是“ hello world”,但应该仅仅是“ world”。 我猜方法getNodeValue()返回null,因为节点类型为ELEMENT_NODE。 无论如何,我有一个问题:我怎样才能只获得标签A的价值,才能获得“世界”的价值? 谢谢。
我没有对其进行测试,但是我相信下面的代码应该可以工作:
private TagA parseTagA(Node node) {
TagA tagA = new TagA();
String tagABody = "";
if (node.hasChildNodes()) {
NodeList childList = node.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
// gets child
Node child = childList.item(i);
if(child.getNodeType == Node.TEXT_NODE) {
tagABody = node.getNodeValue();
tagA.setBody(tagABody);
} else
// parse <B> tag
if (child != null && "B".equals(child.getNodeName())) {
tagA.setTagB(parseTagB(child));
}
}
}
return tagA;
}
我建议处理A
元素的文本节点子代。
您可以在正在执行的子节点循环中执行此操作。 if
为您标识B
, if
将具有else
,您将在其中累积非B
文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.