使用Java Dom在XMl中找到标签是否存在 [英] find if a tag exists by name in XMl using Java Dom

查看:1160
本文介绍了使用Java Dom在XMl中找到标签是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在以下示例中使用Java Dom检查XML中是否存在特定的子代:我正在寻找所有 userFiled 的出现,在第一部分中,没有。所以我想说如果没有标签 userField 做某事。

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.

<element class="AufOrgKombination" hash="AOK_1416092142370_76">
    <field name="layer">4</field>
    <field name="name">Function organisation unit combination 1</field>
    <field name="description"/>
</element>
<element class="AufOrgKombination" hash="AOK_1417643334024_77">
    <field name="layer">4</field>
    <field name="name">Function organisation unit combination 1</field>
    <field name="description"/>
    <userField hash="USERFIELD_1415779871581_0">3.0</userField>
    <userField hash="USERFIELD_1415779871581_0">N.A.</userField>
</element>

如下:

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

for (int j = 0, l = NodeuserField.getLength(); j < l; j++) {
    line = (Element) NodeuserField.item(j);
    for (Entry<String, String> userFieldUserDef : map_userField.entrySet()) {
        if (element.getElementsByTagName("hash") == null) {
                                //Do Something
        }
    }
}


推荐答案

p>就像在这个问题一样,我建议再次使用XPath。您可以通过Java XPath API(可能会吸引)或再次使用数据投影(是的,我附属于与此项目)。通过XPath确定一个元素是否存在几种可能性。你可以尝试读取它并测试结果是否为空。这里作为替代:直接声明一个布尔投影方法:<​​/ p>

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<Element> 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

这篇关于使用Java Dom在XMl中找到标签是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆