仅当节点具有属性时,才使用Java在xml中添加节点

时间:2018-12-13 15:02:14

标签: java xml

我有以下xml代码,并且仅在节点具有属性manufacturedMaterial的情况下才想在节点determinerCode中添加注释。

<manufacturedProduct classCode="MANU">
   <manufacturedMaterial classCode="MMAT" determinerCode="KIND">
      <code code="10219000" codeSystem="0.4.0.127.0.16.1.1.2.1" codeSystemName="EDQM" codeSystemVersion="2017-04-14" displayName="Tablet"/>
      </epsos:code>
   </manufacturedMaterial>
   <manufacturedMaterial classCode="MMAT">
      <code code="10219001" codeSystem="0.4.0.127.0.16.1.1.2.2" codeSystemName="EDQM" codeSystemVersion="2017-04-14" displayName="NoTablet"/>
      </epsos:code>
   </manufacturedMaterial>
   </manufacturedProduct>

当前,我的代码如下,但是在两个manufacturedMaterial节点中添加一个新的子代。有没有办法检查它是否具有属性determinerCode

NodeList nodes = dom.getElementsByTagName("manufacturedMaterial");

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        NodeList childNodes = node.getChildNodes();
        Element formCodeEl = dom.createElement("epsos:formCode");
        formCodeEl.setAttribute("code", myCode.get(i));
        node.appendChild(formCodeEl);
    } 

1 个答案:

答案 0 :(得分:2)

您可以检查节点中的属性列表吗?

if(node.getAttributes().getNamedItem("determinerCode") != null)
{
    // Add your node here...
}