I want to print my xml which is coming from an external feed on the console.
When I do
log.debug "${xml}"
I get xml values on the console but not the starting and end tags. For example
<fruits>
<fruit1>apple</fruit1>
<fruit2>orange</fruit2>
</fruits>
Just prints appleorange
Just the values concatenated one after other. What is the best value to handle it. I tried this Best way to pretty print XML response in grails but I get exception at parseText(). I don't know why, because I think the incoming xml is valid.
Update: The type of variable xml is Groovy's NodeChild.
You can do the following, if your xml is simple it should satisfy your needs:
`
def xml = new XmlSlurper().parseText(xmlString)
def result = new StreamingMarkupBuilder().bind{
mkp.yield xml
}
log.debug result as String
`
try this
def writer = new StringWriter()
xml.writeTo(writer)
log.debug writer.toString()
Related
def siteNameChange():File={
for(line<-Source.fromFile("RecordedSimulation_0000_NewSiterequest2.txt").getLines())
if(line.contains("siteUrl"))
println(line)
return new File("RecordedSimulation_0000_NewSiterequest2.txt")
}
val scn = scenario("RecordedSimulation")
.exec(http("request_0")
.post(“/student/new”)
.body(RawFileBodyPart(session=>siteNameChange())).asJSON)
Hello I am a newbie to Gatling, using it for performance testing. I have a function named siteNameChange() which returns a file after doing some modifications on the file.
This function I am calling in the scenario body to send the data.
But when I am running the script I am getting scala:48:26: missing parameter type
.body(RawFileBodyPart(session=>siteNameChange())).asJSON)
Can some one please suggest whats the best thing to do this here, how to get the function return the modified file and pass the file data over the post request
body doesn't take a BodyPart (which is for multipart) parameter but a Body one.
You should be passing a RawFileBody.
I'm trying to use groovy to update Jenkins job config.xml by the following code
def updateParameter(String key, String value){
println "changing defult value as $value for key $key"
def xml = new XmlSlurper().parseText(jobConfig)
xml.properties.'hudson.model.ParametersDefinitionProperty'.'parameterDefinitions'.'hudson.model.StringParameterDefinition'.each {
println 'found parameter: ' + it.name
if(it.name.text() == key){
println('default value changed')
it.defaultValue=value
}
}
jobConfig = XmlUtil.serialize(xml)
}
When running jobConfig = XmlUtil.serialize(xml), it changes the format, which is pretty, but I lost link break in pipeline plugin, so pipeline script doesn't work anymore. Is there a way to convert GPathResult to String without format changing?
Best Regards,
Eric
It is all my fault, the line breaks were removed when I read the xml. It seems XmlUtil.serialize(xml) doen't format the text of a xml tag, which is good :)
Best Regards,
Eric
I'm trying to use a groovy Config entry to parse an xml file with XmlSlurper.
Here's the Config file:
sample {
xml {
frompath = "Email.From"
}
}
Here's the XML
<xml>
<Email>
<From>
<Address>foo#bar.com</Address>
<Alias>Foo Bar</Alias>
</From>
<Email>
</xml>
This is what I tried initially:
XmlSlurper slurper = new XmlSlurper()
def record = slurper.parseText((new File("myfile.xml")).text)
def emailFrom = record?."${grailsApplication.config.sample.xml.frompath}".Address.text()
This doesn't work because XmlSlurper allows one to use special characters in path names as long as they're surrounded by quotes, so the app is translating this as:
def emailFrom = record?."Email.From".Address.text()
and not
def emailFrom = record?.Email.From.Address.text()
I tried setting the frompath property to be "Email"."From" and then '"Email"."From"'. I tried tokenizing the property in the middle of the parse statement (don't ask.)
Can someone please point me towards some resources to find out if/how I can do this?
I feel like this issue getting dynamic Config parameter in Grails taglib and this https://softnoise.wordpress.com/2013/07/29/grails-injecting-config-parameters/ may have whispers of a solution, but I need fresh eyes to see it.
The solution in issue getting dynamic Config parameter in Grails taglib is a proper way to deref down such a path. E.g.
def emailFrom = 'Email.From'.tokenize('.').inject(record){ r,it -> r."$it" }
def emailFromAddress = emailFrom.Address.text()
If your path there can get complex and you rather go with the potentially more dangerous way, you could also use Eval. E.g.
def path = "a[0].b.c"
def map = [a:[[b:[c:666]]]] // dummy map, same as xmlslurper
assert Eval.x(map, "x.$path") == 666
I have so many texts in log file but sometimes i got responses as a xml code and I have to cut this xml code and move to other files.
For example:
sThread1....dsadasdsadsadasdasdasdas.......dasdasdasdadasdasdasdadadsada
important xml code to cut and move to other file: <response><important> 1 </import...></response>
important xml code to other file: <response><important> 2 </important...></response>
sThread2....dsadasdsadsadasdasdasdas.......dasdasdasdadasdasdasdadadsada
Hindrance: xml code starting from difference numbers of sign (not always start in the same number of sign)
Please help me with finding method how to find xml code in text
Right now i tested substring() method but xml code not always start from this same sign :(
EDIT:
I found what I wanted, function which I searched was indexOf().
I needed a number of letter where String "Response is : " ending: so I used:
int positionOfXmlInLine = lineTxt.indexOf("<response")
And after this I can cut string to the end of the line :
def cuttedText = lineTxt.substring(positionOfXmlInLine);
So I have right now only a XML text/code from log file.
Next is a parsing XML value like BDKosher wrote under it.
Hoply that will help someone You guys
You might be able to leverage XmlSlurper for this, assuming your XML is valid enough. The code below will take each line of the log, wrap it in a root element, and parse it. Once parsed, it extracts and prints out the value of the <important> element's value attribute, but instead you could do whatever you need to do with the data:
def input = '''
sThread1..sdadassda..sdadasdsada....sdadasdas...
important code to cut and move to other file: **<response><important value="1"></important></response>**
important code to other file: ****<response><important value="3"></important></response>****
sThread2..dsadasd.s.da.das.d.as.das.d.as.da.sd.a.
'''
def parser = new XmlSlurper()
input.eachLine { line, lineNo ->
def output = parser.parseText("<wrapper>$line</wrapper>")
if (!output.response.isEmpty()) {
println "Line $lineNo is of importance ${output.response.important.#value.text()}"
}
}
This prints out:
Line 2 is of importance 1
Line 3 is of importance 3
I have an XML as input to a Java function that parses it and produces an output. Somewhere in the XML there is the word "stratégie". The output is "stratgie". How should I parse the XML as to get the "é" character as well?
The XML is not produced by myself, I get it as a response from a web service and I am positive that "stratégie" is included in it as "stratégie".
In the parser, I have:
public List<Item> GetItems(InputStream stream) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("item");
List<Item> items = new ArrayList<Item>();
Item currentItem = new Item();
Node node = nodeLst.item(0);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element item = (Element) node;
if(node.getChildNodes().getLength()==0){
return null;
}
NodeList title = item.getElementsByTagName("title");
Element titleElmnt = (Element) title.item(0);
if (null != titleElmnt)
currentItem.setTitle(titleElmnt.getChildNodes().item(0).getNodeValue());
....
Using the debugger, I can see that titleElmnt.getChildNodes().item(0).getNodeValue() is "stratgie" (without the é).
Thank you for your help.
I strongly suspect that either you're parsing it incorrectly or (rather more likely) it's just not being displayed properly. You haven't really told us anything about the code or how you're using the result, which makes it hard to give very concrete advice.
As ever with encoding issues, the first thing to do is work out exactly where data is getting lost. Lots of logging tends to be the way forward: create a small test case that demonstrates the problem (as small as you can get away with) and log everything about the data. Don't just try to log it as raw text: log the Unicode value of each character. That way your log will have all the information even if there are problems with the font or encoding you use to view the log.
The answer was here: http://www.yagudaev.com/programming/java/7-jsp-escaping-html
You can either use utf-8 and have the 'é' char in your document instead of é, or you need to have a parser that understand this entity which exists in HTML and XHTML and maybe other XML dialects but not in pure XML : in pure XML there's "only" ", <, > and maybe ' I don't remember.
Maybe you can need to specify those special-char entities in your DTD or XML Schema (I don't know which one you use) and tell your parser about it.