Monday, October 31, 2011

Parsing XML and iterating it using XPath

How to parse XML from a string and iterate over a specific node name using Xpath

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder = dbf.newDocumentBuilder();
String string = xmlBuffer.toString();
// not to parse a string you have to pass it in via stream
Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(string.getBytes("utf-8"))));

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
// match all nodes where the tag name is column and get the text content.
XPathExpression expr = xpath.compile("//column/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {" "+nodes.item(i).getNodeValue());

Xcelsius Send and Recieve XML with Servlet

Xcelsius is a great tool to quickly wire up dashboards and reports without much coding. However there is the need to sometimes integrate it with dynamic data. You can create an XML data connection to query values from the database and associate it to your Xcelsius Model file.

  • Following are the steps :-
    • Create an XML data connection.
    • Enter an URL for the xml data connection for Example /servlet/service/BusinessInfoServlet?mode=query 
    • Click on the "+" symbol to add a variable name
    • The name that comes up on the screen is your variable name. Please note that. 
    • Click on the cell icon to select the range of cells that you want to associate your database result to your excel model.
    • Select Enable Load
    • In your servlet 
    PrintWriter out = response.getWriter();
    String xmlContent = ""+xmlBuffer.toString()+"";
            • The structure of your XML buffer is mapped as rows and columns.  
            •  The variable attribute name should map to the name in the XML data connection. 
            • Also note the row vs column structure, for multiple rows you need to iterate your tags like that.

            <variable name="Range_0" >

          Works on My Machine

          Post on "When developers say it worked