Thursday, August 16, 2012

Jdom CRUD Operations

Hi,

Jdom CRUD Operations

Here is sample code to do some operations like
   
//Adding elements
    public void addElementAtXpath() {
        try {
            XPath xpath = XPath.newInstance("publishers");
            xpath.addNamespace(root_.getNamespace());
            Element publisherNode = (Element) xpath.selectSingleNode(root_);
            org.jdom.Element element = new Element("kalees");
            element.addContent(createElement(CI_FILE_RELEASE_OVERRIDE_AUTH_NODE, TRUE));
            publisherNode.addContent(element);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
// Changing attributes
    public void changeAttributeValue() {
        try {
            XPath xpath = XPath.newInstance("scm");
            xpath.addNamespace(root_.getNamespace());
            Element scmNode = (Element) xpath.selectSingleNode(root_);
            scmNode.setAttribute("class", "Kalees");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
//Deleting Elements
    public void deleteElementAtXpath() {
        //deleting a node...
        // deleting content of a node
        //triggerNode.removeContent();
        try {
            String childName = "hudson.plugins.emailext.ExtendedEmailPublisher";
            XPath xpath = XPath.newInstance("publishers");
            xpath.addNamespace(root_.getNamespace());
            Element triggerNode = (Element) xpath.selectSingleNode(root_); // if it is null then element is not present
            triggerNode.removeChild(childName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Element createElement(String nodeName, String NodeValue) {
        org.jdom.Element element = new Element(nodeName);
        if (NodeValue != null) {
            element.addContent(NodeValue);
        }
        return element;
    }
--
Thank you.


Regards,
Kaleeswaran.S

No comments:

Post a Comment