Groovy - XmlSlurper - find innermost element - groovy

I have the following xml:
<vehicle>
<car>
<price>100</price>
<price>200</price>
</car>
<car>
<price>300</price>
<price>400</price>
</car>
</vehicle>
Given an xml, how can we get the innermost elements (in this case, all the<price> elements)?

Assuming you have the xml in a String xml, you should be able to do:
List prices = new XmlSlurper().parseText( xml ).car.price*.text()​​

thanks Tim for the answer. I just figured out the following works too. And is more generic:
def document = slurper.parseText(xml)
def prices = document.'**'.findAll { it.children().size() == 0 }

May I suggest you next variant:
def vehicle = new XmlSlurper().parseText(xmlString)
vehicle.car.price.each {println "car's price:"+it}

Related

How to get first String based on whitespace out of a full String using java8?

Let's Example I have String s = "Rahul Kumar" I need to have Rahul as a output using java8
Actual Requirement, I do have a list of Trip Object, I want to set driverName property as only first name to each Trip Object and return that list?
System.out.println( someStringValue.subSequence(0, someStringValue.indexOf(' ')));
I'm getting trouble to incorporate this code into the listOfTrip. If I'm doing like this,
List<CharSequence> list = listOfTrips.stream().map(e -> e.getDriverName().subSequence(0, someStringValue.indexOf(' '))).collect(Collectors.toList()); System.out.println(list);
Here, With this, The return type is wrong and it is not fetching only first name out of full name.
Below will give you the proper result:
List<CharSequence> list2 = listOfTrips.stream()
.map(m->m.getDriverName().substring(0,m.getDriverName().indexOf(' ')))
.collect(Collectors.toList());
Please try this also once:
String s = "Rahul Kumar";
Optional<String> beforeWhiteSpace = Pattern.compile(" ").splitAsStream(s).collect(Collectors.toList()).stream().findFirst();

(Groovy) Add multiple values to an ArrayList

like the title says, I want to add multiple values to my arrayList in Groovy.
But it is not accepted.
Collection<String> actorCollection = new ArrayList<>();
actorCollection.add("first","second");
If there is only a single value, it works perfectly.
Thanks in advance!
Use addAll: actorCollection.addAll("first","second")
Note: Groovy's list literal will give you an array list. So could just write def actorCollection = [] or even ... = ["first", "second"] to fill the list with the values right from the beginning.

To Get Tag value by passing Tag name from a string in XML Parser method in Groovy

How can I get the value of any tag (e.g. Quantity) from the below XML by passing the tag name without using hard coded tag name-
def temp1="""
<TradeRecord>
<TradeId>1000</TradeId>
<SecurityId>10382456</SecurityId>
<TradeType>SELLL</TradeType>
<TradeDate>2014-03-21</TradeDate>
<Broker>100</Broker>
<Exchange>1</Exchange>
<Status>INIT</Status>
<Quantity>125</Quantity>
<ApprovedBy />
</TradeRecord>
"""
def records = new XmlParser().parseText(temp1)
//log.info records.Quantity[0].text() By using this i am getting value but i want 'Quantity' to come from a string
tag = 'Quantity'
xy = records["Quantity"].value; 'This is not working
log.info xy
You should be able to do
records."$tag".text()
You should have used .text() method
records[tag].text()

groovy only grabbing first element of loop

I've got a very straightforward code snippet. That for some reason is
only grabbing the first element of the loop when I try to output it in
my jsp. JcrUtils.getChildNodes returns a NodeIterator that I thought would loop through
each property. Here is the code:
def headerNode = JcrUtils.getChildNodes(LINKS).find{
it.hasProperty("headerTitle")
it.hasProperty("headerMeta")
}
selectHeaderTitle = headerNode.getProperty("headerTitle").getString()
selectHeaderMeta = headerNode.getProperty("headerMeta").getString()
JSP:
${header.selectHeaderTitle}
${header.selectHeaderMeta}
Any help is greatly appreciated!
You want a list of Properties? You'd need findAll, also you need to && your hasProperty calls:
def headerNode = JcrUtils.getChildNodes(LINKS).findAll {
it.hasProperty("headerTitle") && it.hasProperty("headerMeta")
}
Groovy find only returns the first match.
See http://groovy.codehaus.org/Iterator+Tricks

Magento: getting attributes from an attribute set without a product

I have set an attribute set in my Magento shop which has several binary attributes.
For a pulldown I need a list of ALL the attributes inside this one attribute set, including their internal name and their label. Since this pulldown should appear in places that not necessarily have a product selected I can't go the usual route of "getting the attributes of a product".
How do I go about of getting a list of all the attributes inside my set?
OK, I realised that I missed that you want the whole set of attributes, not just an individual one. Try this:
$productEntityType = Mage::getModel('eav/entity_type')->loadByCode(Mage_Catalog_Model_Product::ENTITY);
$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection');
$attributesInfo = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($productEntityType->getId()) //4 = product entities
->addSetInfo()
->getData();
You'll then need to iterate through the array that is returned with something like:
foreach($attributesInfo as $attribute):
$attribute = Mage::getModel('eav/entity_attribute')->load($attribute['attribute_id']);
echo 'label = '.$attribute->getFrontendLabel().'<br/>';
echo 'code = '.$attribute->getAttributeCode().'<br/><br/>';
endforeach;
Sorry for missing the original point, hope this helps!
Cheers,
JD
In order to get all the attributes in an attribute set, you can use as:
$entityTypeId = Mage::getModel('eav/entity')
                ->setType('catalog_product')
                ->getTypeId();
$attributeSetName   = 'Default'; //Edit with your required Attribute Set Name
$attributeSetId     = Mage::getModel('eav/entity_attribute_set')
                    ->getCollection()
                    ->setEntityTypeFilter($entityTypeId)
                    ->addFieldToFilter('attribute_set_name', $attributeSetName)
                    ->getFirstItem()
                    ->getAttributeSetId();
$attributes = Mage::getModel('catalog/product_attribute_api')->items($attributeSetId);
foreach($attributes as $_attribute){
    print_r($_attribute);
}
Cheers!!
try this snippet, it should give you want you need, except for multi-select attributes.
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product','attribute_name');
foreach($attribute->getSource()->getAllOptions(true,true) as $option){
$attributeArray[$option['value']] = $option['label'];
}
return $attributeArray;
Hope this helps,
JD

Resources