Parse XML from String using XPath in Bada? - string

I have read the tutorial on XML parsing in Bada. But I don't want to use a file. I need to parse my XML from a Osp::Base::String. Any ideas which methods should I use? So far I have replaced
xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL) {
AppLog("Error: unable to create new XPath context");
xmlFreeDoc(doc);
return(E_IO);
}
with
xpathCtx = (xmlXPathContextPtr) xmlXPathNewCString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><title lang=\"en\">XQuery Kick Start</title><title lang=\"en\">Learning XML</title>");
But the emulator simply closes.
Thank you.

Your code is wrong because you cannot cast from xmlXPathObjectPtr to xmlXPathContextPtr: they are different structs.
The code given in the tutorial is right, just use
xmlDocPtr xmlReadDoc (const xmlChar * cur,
const char * URL,
const char * encoding,
int options)
instead of
xmlReadFile(..)
To understand how to use this function have a look at the docs and at the examples on libXML2 website.

Related

Getting a Fail Trying to Parse a ZonedDateTime from a String Using ZonedDateTimePattern

I've been learning how to use NodaTime, as I think it is a far superior "all things temporal" library that the handful of structs in the BCL. Reading the docs and experimenting.
This experiment has me flummoxed. I started out just trying to parse a ZonedDateTime.
The things I was trying were not successful, so I thought I'd try something which should be "bulletproof". The following code represents that attempt:
Instant thisNow = SystemClock.Instance.GetCurrentInstant();
var timezone = DateTimeZoneProviders.Tzdb["Australia/Brisbane"];
var zonedDateTime = thisNow.InZone(timezone);
var zonePattern = ZonedDateTimePattern.GeneralFormatOnlyIso;
var zoneFormatted = zonePattern.Format(zonedDateTime);
var zoneParseResult = zonePattern.Parse(zoneFormatted);
Console.WriteLine(zoneParseResult.Success ? "parse success" : "parse failure");
So, simply trying to parse back that which you just converted to a string.
The zoneFormatted has the following value 2021-09-04T16:59:08 Australia/Brisbane (+10)
Any ideas what I am doing wrong?
Cheers
Any ideas what I am doing wrong?
You're using ZonedDateTimePattern.GeneralFormatOnlyIso, which is (as the name suggests) only for formatting, not for parsing.
To get a pattern which is able to parse time zones, you need to specify an IDateTimeZoneProvider. The easiest way to do that is to start with a format-only pattern, and use WithZoneProvider:
using NodaTime;
using NodaTime.Text;
using System;
class Program
{
static void Main(string[] args)
{
var pattern = ZonedDateTimePattern.GeneralFormatOnlyIso
.WithZoneProvider(DateTimeZoneProviders.Tzdb);
var text = "2021-09-04T16:59:08 Australia/Brisbane (+10)";
var result = pattern.Parse(text);
Console.WriteLine(result.Success);
Console.WriteLine(result.Value);
}
}

Importing a modified String class from another file in nodejs

I have added to the String class three prototype classes on a file classed parse.js:
String.prototype.parseCropTo = function (needle) {
if (this.includes(needle) === false) return false;
return this.slice(0, this.indexOf(needle)).trim();
}
String.prototype.parseCropFrom = function (needle) {
if (this.includes(needle) === false) return false;
return this.slice(this.indexOf(needle) + needle.length).trim();
}
String.prototype.parseCropBetween = function (needleFrom, needleTo) {
let haystack = this.parseCropFrom(needleFrom);
if (haystack != false) return haystack.parseCropTo(needleTo);
}
As far as I can see, imported files have to expose specific functions and then they are called via a variable. However, I wish to import parse.js to other files so I could use these functions directly on strings:
let haystack = 'This is a lovely day';
console.log(haystack.parseCropBetween('is', 'day'));
Is this possible? thanks in advance.
By extending the prototype of String, you will have these methods on every string you'll ever use, however you need to load it somewhere in your code, because you won't be able to use that beforehand.
The reason that works is because your'e accessing String.prototype by reference, as with all non-primitive types in javascript so calling it once, will get you set for the rest of your code.
Generally speaking, it's not advised to extend native constructs.
See full example here:
https://codesandbox.io/s/epic-cerf-4qshv?file=/src/App.js
Additionally, I'd advise you to read some opinions about extending prototypes in javascript and considers the pros and cons of this approach:
Why is extending native objects a bad practice?

nodejs xml2j how do I skipPrefix

I have read the documentation but I can't quite seem to get the skipPrefix to work with xml2js. What I would like do to do is given the following xml remove the namespace prefix.
<root>
<part:tire>A</part:tire>
</root>
I would like the json object to exclude "part:".
Thanks
From the source code
prefixMatch = new RegExp(/(?!xmlns)^.*:/);
...
exports.stripPrefix = function(str) {
return str.replace(prefixMatch, '');
};
i think your xml string need to have proper namespace in order for that feature to work.

customized error reporting in v4

Another question on migrating code from v3 to v4:
For v3, I had a customized error reporting, using code like this (in the grammar file):
#members {
public void displayRecognitionError(String[] tokenNames,
RecognitionException e) {
String hdr = getErrorHeader(e);
String msg = getErrorMessage(e, tokenNames);
System.out.println("ERR:"+hdr+":"+msg);
errCount += 1;
}
}
In v4, when compiling the generated java files, I am getting the error:
MyParser.java:163: cannot find symbol
symbol : method getErrorMessage(org.antlr.v4.runtime.RecognitionException,java.lang.String[])
location: class MyParser
String msg = getErrorMessage(e, tokenNames);
^
Is this function replaced by some other function in v4? (I saw some questions and answers on ANTLRErrorListener, but I could not get how to use it for my situation.)
The displayRecognitionError method was removed in ANTLR 4, so even if you correct the body of that method it will not do anything. You need to remove the method from your grammar entirely, and implement ANTLRErrorListener instead. The documentation includes a list of classes that implement the interface, so you can reference those and/or extend one of them to produce the desired functionality.
Once you have an instance of an ANTLRErrorListener, you can use the following code to attach it to a Parser instance.
// remove the default error listener
parser.removeErrorListeners();
// add your custom error listener
parser.addErrorListener(listener);

Can groovy heredocs be internationalized?

Have some multiline strings that are presented to the user and stored as Heredocs. So rather than a 'normal' (Java) property file, a groovy-based one (see here) to be consumed by ConfigSlurper was used and works great. Sorry if this is a dumb question, but can that be easily internationalized? If so, can you outline how that is accomplished?
My solution: In your ConfigSlurper you should store keys to the internalized strings. Inject messageSourceand localResolver in your controller/service, get key from your ConfigSlurper and find localized string in your i18n messages.property file. Example (not sure that code is correct, but it's the main idea):
def config = new ConfigSlurper().parse(new File('src/Config.groovy').toURL())
//localized string1 value
def msg = messageSource.getMessage(config.data1.string1, null, localeResolver.defaultLocale)
As far as I know the ConfigSlurper does not have special support for i18n.
You may achieve it by using the leveraging its support for environments by creating an environment closure per locale. For example:
environments {
english {
sample {
hello = "hello"
}
}
spanish {
sample {
hello = "hola"
}
}
}
When creating the ConfigSlurper you will need to pass the desired language:
def config = new ConfigSlurper("spanish")

Resources