Home > Back-end >  Adding attribute to xml subtag
Adding attribute to xml subtag

Time:09-26

I'm working in Java 8- this seems like a very simple problem, but I'd like to know if I'm missing something. XML looks like this.

<supertag>
    <subtag1 attr1='1' attr2='2'/>
    <subtag2>body</subtag2>
</supertag>

I'd like to add an attribute "attr3" to subtag1.

Relevant code so far (xmlPacket is an org.w3c.dom)-

NodeList subtag1 = xmlPacket.getElementsByTagName("subtag1");
for (int i = 0; i < subtag1.getLength(); i  ) {
 Node nNode = subtag1.item(i);
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
       Element eElement = (Element) nNode;
       eElement.setAttribute("attr3", "3");
    }
}

This currently turns the xmlPacket to document[#null].

What am I missing here? Thanks!

P.S.- I'd like to add that I'm able to retrieve attribute values by using eElement.getAttribute("attr1");

CodePudding user response:

Remember to convert your document back to an XML string, the toString Method will result in the document[#null] error.

Refer to this answer here.

  • Related