如何在以下示例中使用Java Dom检查XML中是否存在特定的子代码:我正在查找所有userFiled
次出现,而在第一部分中,没有。所以我想说如果没有标记userField
做某事。
<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
}
}
}
答案 0 :(得分:0)
就像在this question中一样,我建议再次使用XPath。你可以通过Java XPath API(很糟糕)来做,或者再次使用data projection(是的,我是这个项目的附属机构)。如果存在元素,通过XPath确定有几种可能性。您可以尝试读取它并测试结果是否为null。这里作为替代方案:直接声明一个布尔投影方法:</ p>
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");
}
}
}
此程序打印出来
Element with hash 'AOK_1416092142370_76' has no user field
Element with hash 'AOK_1417643334024_77' has user field