java判断xml 子节点是否存在,使用Java Dom在XMl中找到标签是否存在

How can I check if a specific child dose not exist in XML using Java Dom in the following sample: I am looking for all userFiled occurrences and in the first part, there are none. So I want to say if there is no tag userField do something.

4

Function organisation unit combination 1

4

Function organisation unit combination 1

3.0

N.A.

something like:

NodeList NodeuserField = element.getElementsByTagName("userField");

Element line;

for (int j = 0, l = NodeuserField.getLength(); j < l; j++) {

line = (Element) NodeuserField.item(j);

for (Entry userFieldUserDef : map_userField.entrySet()) {

if (element.getElementsByTagName("hash") == null) {

//Do Something

}

}

}

解决方案

Just like in this question I suggest using XPath again. You can do it via the Java XPath API (which sucks), or again use data projection (Yes, I'm affiliated with this project). There are several possibilities to determine via XPath if an element exist. You could just try to read it and test if the result is null. Here as an alternative: Declaring directly a boolean projection method:

public class ElementExists {

public interface Projection {

interface Element {

@XBRead("./@hash")

String getHash();

@XBRead("count(./userField)>0")

boolean hasUserField();

}

@XBRead("//element")

List getElements();

}

public static void main(final String[] args) throws IOException {

Projection projection = new XBProjector().io().url("resource://data.xml").read(Projection.class);

for (Projection.Element e : projection.getElements()) {

System.out.print("Element with hash '" + e.getHash() + "' has ");

System.out.println((e.hasUserField() ? "" : "no ") + "user field");

}

}

}

This program prints out

Element with hash 'AOK_1416092142370_76' has no user field

Element with hash 'AOK_1417643334024_77' has user field

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值