I know I can hardcode it (parse xml, extract), but is there a way to feed (attribute value + nodevalue) like it is done with Feed4TestNG (it currently support only csv, and excel files)?
I am new to Java, and any expert insight would be helpful. Thanks!
The body of a #Parameters is not limited to data only, you are able to use any java code you like in this method, including throwing exceptions:
#Parameters
public static Collection<Object[]> data() throws IOException {
List<Object[]> data = new ArrayList<>();
// replace getClass() with <nameofclass>.class
try(InputStream in = this.getClass().getResourceAsStream()) {
//parse body here
data.add(new Object[]{attribute, value});
}
return data;
}
Depending on what XML framework you use, you need to parse your XML nodes, and put it in the list, that you are going to return.
So this is what I end up doing here:
Please submit your correction if you think I can improve my code.
.
#RunWith(Parameterized.class)
public class DataDrivenTests {
private String c;
private String b;
private static Collection<Object[]> a;
#Parameters
public static Collection<Object[]> xmlData() throws IOException{
File file = new File("xmlfile.xml");
InputStream xml1 = new FileInputStream(file);
return new xmlData(xml1).getData();
}
public DataDrivenTests(String c, String b) {
super();
this.c = c;
this.b = b;
}
#Test
public void shouldCalculateATimesB() {
boolean assertion = false;
if(c.equals(Parser.parse("Parse this string to Attribute and Value"))){
assertion = true;
}
assertTrue(assertion);
}
}
xmlData.java
public class xmlData{
private transient Collection<Object[]> data = null;
public xmlData(final InputStream xml)throws IOException{
this.data = loadFromXml(xml);
}
public Collection<Object[]> getData(){
return data;
}
private Collection<Object[]> loadFromXml(final InputStream xml)
throws IOException {
List <Object[]> ism_code_map = new ArrayList<Object[]>();
try{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile("//e");
NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
for (int i =0; i< nodes.getLength(); i++){
Node nNode = nodes.item(i);
//System.out.println("\nCurrent Element:" + nNode.getTextContent());
if (nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
if(eElement.getAttribute("attrname") != null && !eElement.getAttribute("attrname").isEmpty()){
code_map.add(new Object[]{"attrname",eElement.getAttribute("attrname")});
}
}catch(ParserConfigurationException e){
e.printStackTrace();
}catch(SAXException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(XPathExpressionException e){
e.printStackTrace();
}
catch(NullPointerException e){
e.printStackTrace();
}
return code_map;
}
}
Related
I want to update a PowerPoint template using Java and Aspose library:
For Example:
I have key and value in ppt as
firstname:${firstname}
lastname:${lastname}
I have an XML file which contains below data:
<firstname> Arjun </firstname>
<lastname> Rathore</lastname>
I want to dynamically update the ppt firstname with Arjun and lastname with Rathore.
i have tried below code to replace text in ppt templae using Aspose but replacement is not happening as per expectation.
String path="C:\\workspace\\src\\main\\resources\\testdata\\";
Presentation presentation = new Presentation(path+"sample.pptx");
presentation.joinPortionsWithSameFormatting();
String strToReplace = "Done";
ITextFrame[] tb = SlideUtil.getAllTextFrames(presentation, true);
String strToFind = "sample";
System.out.println("Before for");
for (int i = 0; i < tb.length; i++)
{
for (IParagraph ipParagraph : tb[i].getParagraphs())
{
ipParagraph.getText().replace(strToFind,strToReplace);
System.out.println("replaced");
for (IPortion iPortion : ipParagraph.getPortions())
{
if (iPortion.getText().toLowerCase().contains(strToFind.toLowerCase()))
{
iPortion.setText(iPortion.getText().toLowerCase().replace(strToFind,strToReplace));
System.out.println("replaced");
}
}
}
}
presentation.save(path+"Output.pptx",SaveFormat.Pptx);
Please find below attachment for reference:
1)input_ppt_template
input_ppt_template screenshot
2)input_xml_data
input_xml_data screenshot
3)expected_output_ppt
expected_output_ppt screenshot
I have observed the images shared by you and based on that created a sample application that shall do the replacement of the text based on data read from XML file. Please try using following sample example for your kind reference.
public static void TestTextReplacment()
{
String path="C:\\Aspose Data\\XMLdata\\";
Presentation presentation = new Presentation(path+"TextToReplace.pptx");
List<Data>ListData=LoadXML();
String[] strToFindArray= {"{{clientName}}","{{contactNumber}}","{{contactAddress}}"};
presentation.joinPortionsWithSameFormatting();
String strToReplace = "Done";
ITextFrame[] tb = SlideUtil.getAllTextFrames(presentation, true);
System.out.println("Before for");
for(int x=0;x<strToFindArray.length;x++)
{
String strToFind=strToFindArray[x];
for (int i = 0; i < tb.length; i++)
{
for (IParagraph ipParagraph : tb[i].getParagraphs())
{
//ipParagraph.getText().replace(strToFind,strToReplace);
//System.out.println("replaced");
for (IPortion iPortion : ipParagraph.getPortions())
{
if (iPortion.getText().toLowerCase().contains(strToFind.toLowerCase()))
{
System.out.println(iPortion.getText());
//iPortion.setText(iPortion.getText().toLowerCase().replace(strToFind,strToReplace));
if(x==0)
{
iPortion.setText(iPortion.getText().toLowerCase().replace(strToFind.toLowerCase(),ListData.get(0).clientName));
}
else if(x==1)
{
iPortion.setText(iPortion.getText().toLowerCase().replace(strToFind.toLowerCase(),ListData.get(0).clientNumber));
}
else
{
iPortion.setText(iPortion.getText().toLowerCase().replace(strToFind.toLowerCase(),ListData.get(0).clientAddress));
}
System.out.println("After: "+ iPortion.getText());
System.out.println("replaced");
}
}
}
}
}
presentation.save(path+"Output.pptx",SaveFormat.Pptx);
}
public static List<Data> LoadXML()
{
File file = new File("C:\\Aspose Data\\XMLdata\\TestData.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder;
Document document=null;
try
{
documentBuilder = documentBuilderFactory.newDocumentBuilder();
document = documentBuilder.parse(file);
}
catch (Exception e)
{
e.printStackTrace();
}
NodeList nList = document.getElementsByTagName("data");
List<Data> dataList=new ArrayList<Data>();
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Data data=new Data();
Element eElement = (Element) nNode;
System.out.println(eElement.getNodeName());
data.clientName=eElement.getElementsByTagName("clientName").item(0).getChildNodes().item(0).getNodeValue();
data.clientNumber=eElement.getElementsByTagName("clientNumber").item(0).getChildNodes().item(0).getNodeValue();
data.clientAddress=eElement.getElementsByTagName("clientAddress").item(0).getChildNodes().item(0).getNodeValue();
dataList.add(data);
}
}
return dataList;
}
I have created a Data class to load data from XML.
public class Data {
public String clientName;
public String clientNumber;
public String clientAddress;
Data()
{
clientName="";
clientNumber="";
clientAddress="";
}
public String getclientName(){return clientName;}
public String getclientNumber(){return clientNumber;}
public String getclientAddress(){return clientAddress;}
public void setclientName(String ClientName){clientName=ClientName;}
public void setclientNumber(String ClientNumber){clientNumber=ClientNumber;}
public void setclientAddress(String ClientAddress ){clientAddress=ClientAddress;}
}
Attached here, please source presentation, source XML and generated output presentation for your reference. I hope the shared example will be helpful to you now.
I am working as Support developer/ Evangelist at Aspose.
in my case its not full xml instead of that i want to parse the part of one xml tag to be parsed.
<FILTERABLE>
<FILTER_ELEMENT ALIAS_NAME="roomnumber" JOINER="AND" LPAREN="false" OPERATOR="BEGINS" RPAREN="false" SEQNUM="1" VALUE="1001"/>
</FILTERABLE>
Please help to convert the code into java object.
ByteArrayInputStream bis = new ByteArrayInputStream(filterStrValue.getBytes("UTF-8"));
Document document = EntityCollectionXMLUtil.DomfromXML(new InputSource(bis), false);
Element rootElement = document.getDocumentElement();
rootElement.getElementsByTagName("FILTERABLE")
Need one java object as a pair of hash map contains below
FILTER_ELEMENT ALIAS_NAME = "roomnumber"
JOINER="AND"
LPAREN="false"
OPERATOR="BEGINS"
RPAREN="false"
SEQNUM="1"
VALUE="1001"
dom4j is an open source, Java-based library for parse XML documents. in this answer used dom4j api for parse the xml document. hence, add the dom4j.jar file into your application's classpath.
class of FILTER_ELEMENT
public class Filter_Element {
private String ALIAS_NAME;
private String JOINER;
private Boolean LPAREN;
private String OPERATOR;
private Boolean RPAREN;
private int SEQNUM;
private int VALUE;
public String getALIAS_NAME() {
return ALIAS_NAME;
}
public void setALIAS_NAME(String aLIAS_NAME) {
ALIAS_NAME = aLIAS_NAME;
}
public String getJOINER() {
return JOINER;
}
public void setJOINER(String jOINER) {
JOINER = jOINER;
}
public Boolean getLPAREN() {
return LPAREN;
}
public void setLPAREN(Boolean lPAREN) {
LPAREN = lPAREN;
}
public String getOPERATOR() {
return OPERATOR;
}
public void setOPERATOR(String oPERATOR) {
OPERATOR = oPERATOR;
}
public Boolean getRPAREN() {
return RPAREN;
}
public void setRPAREN(Boolean rPAREN) {
RPAREN = rPAREN;
}
public int getSEQNUM() {
return SEQNUM;
}
public void setSEQNUM(int sEQNUM) {
SEQNUM = sEQNUM;
}
public int getVALUE() {
return VALUE;
}
public void setVALUE(int vALUE) {
VALUE = vALUE;
}
}
attributes values of xml element (FILTER_ELEMENT) set to the filterElement object
try {
File fXmlFile = new File("your_xml_file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
NodeList nodeList= doc.getElementsByTagName("FILTER_ELEMENT");
Filter_Element filterElement;
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
filterElement = new Filter_Element();
filterElement.setALIAS_NAME(node.getAttributes().getNamedItem("ALIAS_NAME").getNodeValue());
filterElement.setJOINER(node.getAttributes().getNamedItem("JOINER").getNodeValue());
filterElement.setLPAREN(Boolean.valueOf(node.getAttributes().getNamedItem("LPAREN").getNodeValue()));
filterElement.setOPERATOR(node.getAttributes().getNamedItem("OPERATOR").getNodeValue());
filterElement.setRPAREN(Boolean.valueOf(node.getAttributes().getNamedItem("RPAREN").getNodeValue()));
filterElement.setSEQNUM(Integer.valueOf(node.getAttributes().getNamedItem("SEQNUM").getNodeValue()));
filterElement.setVALUE(Integer.valueOf(node.getAttributes().getNamedItem("VALUE").getNodeValue()));
}
} catch (Exception e) {
e.printStackTrace();
}
I'm saving some content from a xml file in a ArrayList, to show in a carousel, so everytime someone enter the website, the xml is downloaded and etc, i don't want that, so i'm saving it in cache using ehcache. But i'm having a problem, in the method to get the Array that is stored, the cache return null, there's nothing there. I'm kinda stuck in this part... maybe i'm getting the cache in a wrong way.
public class xmlCache {
//getting the xml file in a Document
public static Document loadXMLDocument() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(new URL("https://www.w3schools.com/xml/cd_catalog.xml").openStream());
}
//putting the xml content in a ArrayList
public static ArrayList<String> listXML(){
ArrayList<String> xmlList = new ArrayList<String>();
try {
Document doc = xmlCache.loadXMLDocument();
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("CD");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
xmlList.add(eElement.getElementsByTagName("TITLE").item(0).getTextContent() + "|" +
eElement.getElementsByTagName("ARTIST").item(0).getTextContent() + "|" +
eElement.getElementsByTagName("COUNTRY").item(0).getTextContent() + "|" +
eElement.getElementsByTagName("COMPANY").item(0).getTextContent() + "|" +
eElement.getElementsByTagName("YEAR").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return xmlList;
}
//putting the ArrayList in cache
public static void cachingXML () {
ArrayList<String> xmlList = xmlCache.listXML();
CacheManager cacheManager = newCacheManagerBuilder().withCache("basicCache", newCacheConfigurationBuilder(Long.class, ArrayList.class, heap(300).offheap(5, MB)))
.build(true);
Cache<Long, ArrayList> basicCache = cacheManager.getCache("basicCache", Long.class, ArrayList.class);
basicCache.put(1L, xmlList);
ArrayList<String> teste = new ArrayList<>();
// if i do that here, is ok, the return is ok
teste = basicCache.get(1L);
System.out.println(teste.size());
}
//accessing the ArrayList stored
public static ArrayList<String> getTicker() {
ArrayList<String> ticker = new ArrayList<>();
try(CacheManager cacheManager = newCacheManagerBuilder().withCache("basicCache", newCacheConfigurationBuilder(Long.class, ArrayList.class, heap(500).offheap(3, MB)))
.build(true)){
Cache<Long, ArrayList> basicCache = cacheManager.getCache("basicCache", Long.class, ArrayList.class);
//the return is false
System.out.println(basicCache.containsKey(1L));
}catch (Throwable e) {
e.printStackTrace();
}
return ticker;
}
public static void main(String[] args) throws MalformedURLException, SAXException, IOException, ParserConfigurationException {
//this one is ok
xmlCache.cachingXML();
//this one is not
xmlCache.getTicker();
}
}
Without using a namespace the XPath example worked fine. A list is printed. With the namespace added, no result is returned.
How can I use namespaces and XPath properly?
My sample (minimalized) xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<nodespace:Employees xmlns:nodespace="my_unique_namespace_name">
<nodespace:Employee id="1">
<nodespace:age>29</nodespace:age>
<nodespace:name>Pankaj</nodespace:name>
<nodespace:gender>Male</nodespace:gender>
<nodespace:role>Java Developer</nodespace:role>
</nodespace:Employee>
<nodespace:Employee id="2">
<nodespace:age>35</nodespace:age>
<nodespace:name>Lisa</nodespace:name>
<nodespace:gender>Female</nodespace:gender>
<nodespace:role>CEO</nodespace:role>
</nodespace:Employee>
</nodespace:Employees>
The XPath Java source code is:
public class XpathNamespaceTest {
public static final String PREFIX_NAME = "bdn";
public static final String NODESPACE_UNIQUE_NAME = "nodespace";
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
try {
ClassLoader classLoader = new XpathNamespaceTest().getClass().getClassLoader();
URL resource = classLoader.getResource("employees_namespace.xml");
File file = new File( resource.getFile());
builder = factory.newDocumentBuilder();
doc = builder.parse(file);
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
#Override
public Iterator getPrefixes(String arg0) { return null; }
#Override
public String getPrefix(String ns) {
if(ns.equals(NODESPACE_UNIQUE_NAME)) {
return PREFIX_NAME;
}
return null;
}
#Override
public String getNamespaceURI(String arg0) {
if (PREFIX_NAME.equals(arg0)) {
return NODESPACE_UNIQUE_NAME;
}
return null;
}
});
List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath, int age) {
List<String> list = new ArrayList<>();
try {
XPathExpression expr = xpath.compile("/bdn:Employees/bdn:Employee[bdn:age>" + age + "]/bdn:name/text()");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) list.add(nodes.item(i).getNodeValue());
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
}
}
The namespace URI is my_unique_namespace_name so you need
public static final String NODESPACE_UNIQUE_NAME = "my_unique_namespace_name";
i have a xml
<DatosClientes>
<User>Prueba</User>
<intUserNumber>1487</intUserNumber>
<IdUser>1328</IdUser>
</DatosClientes>
How to read data in android ? when run all time return null in node value
public static void Parse(String response){
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(response));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList datos = doc.getElementsByTagName("DatosClientes");
XmlParse parser = new XmlParse();
for (int i = 0; i < datos.getLength(); i++) {
Node node = datos.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("User");
Log.e("log",String.valueOf(nameList.item(0).getNodeValue()));
}
}catch (Exception e){
e.printStackTrace();
}
}
my objetive is finally read value and convert into ArrayList
It sounds like you are trying to get a list of the values in the XML? That is, you want:
{ "Prueba", "1487", "1328" }
For that, you can do something like:
public static final String XML_CONTENT =
"<DatosClientes>"
+ "<User>Prueba</User>"
+ "<intUserNumber>1487</intUserNumber>"
+ "<IdUser>1328</IdUser>"
+ "</DatosClientes>";
public static final Element getRootNode(final String xml) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
return document.getDocumentElement();
} catch (ParserConfigurationException | SAXException | IOException exception) {
System.err.println(exception.getMessage());
return null;
}
}
public static final List<String> getValuesFromXml(final String xmlContent) {
Element root = getRootNode(xmlContent);
NodeList nodes = root.getElementsByTagName("*");
List<String> values = new ArrayList<>();
for (int index = 0; index < nodes.getLength(); index++) {
final String nodeValue = nodes.item(index).getTextContent();
values.add(nodeValue);
System.out.println(nodeValue);
}
return values;
}
public static void main (String[] args) {
final List<String> nodeValues = getValuesFromXml(XML_CONTENT);
}