user3556979
user3556979

Reputation: 5

Modifying an XML in Java

I have an XML document which has null values in its Value tag (something similar to below)

  <ns2:Attribute Name="Store" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
         <ns2:AttributeValue/>
  </ns2:Attribute>

Now, I have to write Java code to modify the values as below.

  <ns2:Attribute Name="Store" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
         <ns2:AttributeValue>ABCDEF</ns2:AttributeValue>
  </ns2:Attribute>

I am using DOM parser to parse the XML. I am able to delete the null tag for " but not able to add new values. I am not even sure if we have a direct way to replace or add the values.

Below is the code I am using to remove the child("")

    Node aNode = nodeList.item(i);
    eElement = (Element) aNode;
    eElement.removeChild(eElement.getFirstChild().getNextSibling());

Thanks in advance

Upvotes: 0

Views: 98

Answers (1)

Hirak
Hirak

Reputation: 3649

Just add data through setTextContent to the element. Sample code is as below:

public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, TransformerException {
    String xml = "<ns2:Attribute Name=\"Store\" NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\"><ns2:AttributeValue/></ns2:Attribute>";
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
    doc.getDocumentElement().normalize();
    NodeList nList = doc.getElementsByTagName("ns2:AttributeValue");
    for (int i=0;i<nList.getLength();i++) {
        Element elem = (Element)nList.item(i);
        elem.setTextContent("Content"+i);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);



System.out.println(nList.getLength());
}

Upvotes: 1

Related Questions