1 Reply Latest reply: Apr 20, 2007 4:12 PM by DrClap RSS

    How to Convert node to element using javax.xml.parsers?

    807606
      Hi:

      I need to parse an xml file and update the attribute of one element and add a new element just before the ending tag. I am using javax.xml.parsers
      ie
      <abc>
      <def hit="1" run="1" default="true/>
      </abc>
      Then the final xml should be
      <abc>
      <def hit="1" run="1"/> <-- element updated
      <ghk hit="1" run="1" /> <-- new element added.
      </abc>

      The only way I know to look for the element def in order to modify is to use
      doc.getElementbyTagName("def"). This returns a NodeList on which I can return getItem() to return a node. There arent any attribute modification methods on the node, so i need to convert it to an element first. How can i do that?
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      
      Document doc = null;
      DocumentBuilder docBuilder = factory.newDocumentBuilder();
      
      File xmlFile = new File(xmlfilepath);
      doc = docBuilder.parse(xmlFile);
      
      Element el = doc.getDocumentElement();
      
      NodeList nl1 = doc.getElementsByTagName("def");
      /*nl1.getItem(0) returns me def as node from the nl1 list, but how can i convert it toElement in order to run an attribute methods on it?*/