Thursday, August 2, 2012
JDOM - How to insert an element, after another
JDOM - How to insert an element, after another
private Document document_ = null;
private Element root_ = null;
@Test
public void generateXml() {
//Url path of the file
String filePath = "http://172.................. .xml";
testXmlGeneration(filePath);
}
private void testXmlGeneration(String url) {
try {
SAXBuilder builder = new SAXBuilder();
// giving xml file url to jdom for parsing
document_ = builder.build(url);
root_ = document_.getRootElement();
// creating necessary elements which is to be appended at a particular point of the location in xml
org.jdom.Element element = new Element("release");
element.addContent(createElement("override", "true"));
element.addContent(createElement("url", "http://outside.out.coml"));
element.addContent(createElement("username", "kaleeswaran"));
element.addContent(createElement("password", "xm0QczqM6k9x10Os1z0k="));
element.addContent(createElement("rpackage", "PackageRed"));
element.addContent(createElement("release", "release"));
element.addContent(createElement("file__patterns", null).addContent(createElement("hudson.plugins.collabnet.documentuploader.FilePattern", "*.zip")));
// i want to add the generated elements after the publish tag in the xml
XPath xpath = XPath.newInstance("publish");
xpath.addNamespace(root_.getNamespace());
Element pullisherNode = (Element) xpath.selectSingleNode(root_);
// here specify the index value where the element should be added and pass the element
pullisherNode.getContent().add(3, element);
File dest = new File("/Users/kaleeswaran/Desktop/gonfig.xml");
InputStream configAsStream = getConfigAsStream();
ciManager.streamToFile(dest, configAsStream) ;
System.out.println("new value added =======> " + url);
} 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;
}
public InputStream getConfigAsStream() throws IOException {
XMLOutputter xmlOutput = new XMLOutputter();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
xmlOutput.output(document_, outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}
--
Thank you.
Regards,
Kaleeswaran.S
Related Posts
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment