在XML JAVA DOM中跳转引用兄弟标记的多个标记

时间:2017-03-23 06:18:58

标签: java xml dom

下面是我的XML。我只想为那些拥有EMPLOYEE_STATUS = 0的人获取GLOBAL_EMP_NO值。

XML:

<GLOBAL_EMP_NO>A12345678</GLOBAL_EMP_NO>
<EMP_NO>12345678</EMP_NO>
<FIRST_NAME>Tushar Furlenco</FIRST_NAME>
<PREF_FIRST_NAME/>
<MIDDLE_NAME/>
<LAST_NAME>Joseph</LAST_NAME>
<PREF_LAST_NAME>Tushar</PREF_LAST_NAME>
<SUFFIX/>
<SMTP_EMAIL>TUSHAR.FURLENCO@EMAIL.COM</SMTP_EMAIL>
<EMPLOYEE_STATUS>0</EMPLOYEE_STATUS>

我尝试了以下语法,它正常工作,并在EMPLOYEE_STATUS = 0时获取GLOBAL_EMP_NO。但我不确定这是否是正确的做法。有人可以就此提出建议吗?

由于

JAVA代码:

Element element = (Element) node;
ArrayList emp0 = new ArrayList();
String emp_status = element.getElementsByTagName("EMPLOYEE_STATUS").item(0).getTextContent();
if (emp_status.equals("0")) {
emp0.add(element.getElementsByTagName("EMPLOYEE_STATUS").item(0).getPreviousSibling().getPreviousSibling().
                    getPreviousSibling().getPreviousSibling().getPreviousSibling().getPreviousSibling().getPreviousSibling()
                    .getPreviousSibling().getPreviousSibling().getPreviousSibling().getTextContent());
}

1 个答案:

答案 0 :(得分:-1)

您是否在寻找类似MCVE的内容?

String xml = "<Root>" +
               "<Item>" +
                 "<No>A123</No>" +
                 "<Other>Foo</Other>" +
                 "<Status>0</Status>" +
               "</Item>" +
               "<Item>" +
                 "<No>B456</No>" +
                 "<Other>Bar</Other>" +
                 "<Status>1</Status>" +
               "</Item>" +
               "<Item>" +
                 "<No>C789</No>" +
                 "<Other>Baz</Other>" +
                 "<Status>0</Status>" +
               "</Item>" +
             "</Root>";
Element root = DocumentBuilderFactory.newInstance().newDocumentBuilder()
               .parse(new InputSource(new StringReader(xml))).getDocumentElement();
NodeList items = root.getElementsByTagName("Item");
for (int i = 0; i < items.getLength(); i++) {
    Element item = (Element) items.item(i);
    if ("0".equals(item.getElementsByTagName("Status").item(0).getTextContent()))
        System.out.println(item.getElementsByTagName("No").item(0).getTextContent());
}

输出

A123
C789