使用Java查找节点值DOM [英] finding node values DOM with in Java

查看:402
本文介绍了使用Java查找节点值DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从XML中获取Java中特定节点的值。

How can I get the value of specific nodes in Java from XML.

我的结构类似于您所看到的结构,我想获取userFileds的值2,NA为第一个,1为最后一个(它是真正的xml数据的一部分,元素的数量更多):

I have structure like what you see bellow and I want to get the values of userFileds(2,N.A. for the first one and 1 for the last one(it is part of real xml data. the number of elements are more):

<element class="AufOrgKombination" hash="AOK_1414931143186_52">
<field name="layer">4</field><field name="name">Function </field>
<field name="description">des</field>
<userField hash="USERFIELD_1415779871581_0">2.0</userField>
<userField hash="USERFIELD_1415386348389_3">N.A.</userField>
</element>
<element class="AufOrgKombination" hash="AOK_1414931143186_23">
<field name="layer">4</field><field name="name">Function 2 </field>
<field name="description">des</field>
<userField hash="USERFIELD_1415779871581_0">1</userField>
</element>


推荐答案

您应该考虑不要使用XPath API, 为您处理的图书馆披露:我隶属于该项目)。您可能希望将XML结构反映到您的对象结构中。有一些困难要克服(命名空间,默认命名空间,类型转换,映射到Java对象,...)。
使用建议库的一个可能的解决方案:

You should consider not to use the XPath API, but a library that handles it for you (Disclosure: I'm affiliated with that project). You probably want to reflect the XML structure somehow to your object structure. There are some difficulties to overcome (Namespaces, default namespaces, type conversion, mapping to Java objects, ...). One possible solution using the suggested library:

public class Demo {

public interface Projection {
    interface Element {
        @XBRead("./userField")
        List<String> getUserFieldValues();
    }

    @XBRead("//element")
    List<Projection.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 element : projection.getElements()) {
        for (String userField : element.getUserFieldValues()) {
            System.out.println(userField);
            }
        }
    }
}

程序打印出来:

2.0
N.A.
1

这篇关于使用Java查找节点值DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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