how to extract values from an xml tree using actionscript - actionscript

I have an xml tree as below
<Response>
<Terminal>
<Name>m1</Name>
<Value><Array1><DBL><Val>-0.143077</Val></DBL></Array1></Value>
</Terminal>
<Terminal>
<Name>m3</Name>
<Value><Array3><DBL><Val>-0.876611</Val></DBL></Array3></Value>
</Terminal>
<Terminal>
<Name>m2</Name>
<Value><Array2><DBL><Val>-0.459437</Val></DBL></Array2></Value>
</Terminal>
</Response>
I have to extract m1,m2,m3 values using action script
Can anyone help me in writing this code .
Is the below code is enough for this
for (var i=0; i<xml.Terminal.length(); i++) {
if (xml.Terminal.Name.text()=="m1") {
voltage=xml.Terminal.Value.Array1.DBL.Val.text()
}
else if (xml.Terminal[i].Name.text()=="m2") {
current=xml.Terminal.Value.Array2.DBL.Val.text();
}
else if (xml.Terminal[i].Name.text()=="m3") {
temperature=xml.Terminal.Value.Array3.DBL.Val.text();
}
}
Menu_Content1.volt_val.text = voltage;
Menu_Content1.curr_val.text = current;
Menu_Content1.temp_val.text = temperature;
)
volt_val.text etc is for text display added in flash.

To parse a common formated tags in XML you have to first place them into a parent tage in your case create XML like this
<Response>
<**PARENT_TAG**>
<Terminal>
<Name>m1</Name>
<Value><Array1><DBL><Val>-0.143077</Val></DBL></Array1></Value>
</Terminal>
<Terminal>
<Name>m3</Name>
<Value><Array3><DBL><Val>-0.876611</Val></DBL></Array3></Value>
</Terminal>
<Terminal>
<Name>m2</Name>
<Value><Array2><DBL><Val>-0.459437</Val></DBL></Array2></Value>
</Terminal>
</**PARENT_TAG**>
</Response>
After that parsing of an XML in actionscript is very easy you just have to create an object of a XML and than use DOM format to get value of a particular tag As an example
var result:XML = new XML(event.target.data);
for(var i:int=0; i<result.PARENT_TAG.length; i++)
{
trace(result.PARENT_TAG.Terminal[i].Name);
}

yes,your idea is lead to right move.but you should first load xml file in object.
You can use XML like here or here in your project.

Related

Remove parent nodes if contains tag

I'm trying to remove url elements from my sitemap if they contain a priority tag. What am I doing wrong?
Script:
<?php
$xml = new DOMDocument;
$xml->load('sitemap.xml');
$priorities = $xml->getElementsByTagName('priority');
foreach($priorities as $priority){
$xml->removeChild($priority);
}
echo $xml->saveXML();
Existing sitemap:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://www.example.tld/</loc></url>
<url><loc>https://www.example.tld/file</loc></url>
<url><loc>https://www.example.tld/folder/</loc><priority>0.7</priority></url>
<url><loc>https://www.example.tld/folder2/</loc><priority>0.3</priority></url>
</urlset>
Desired sitemap:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://www.example.tld/</loc></url>
<url><loc>https://www.example.tld/file</loc></url>
</urlset>
You have to use the parentNode of $priority instead of $xml to remove the child.
Instead of using a foreach, you can loop the collection using a for loop decrementing the value of $i
$xml = new DOMDocument;
$xml->load('sitemap.xml');
$priorities = $xml->getElementsByTagName('priority');
for ($i = $priorities->length - 1; $i >= 0; $i--) {
$priorities[$i]->parentNode->removeChild($priorities[$i]);
}
echo $xml->saveXML();

Show local XML document with WKWebView

I'm trying to display a XML file with WKWebView. Has anyone got it managed to display it? I've set up a complete sample app (see below). The results were obtained by testing on iOS 9.3 iPhone 4S simulator.
LoadFileUrl()
string targetFilepath = Init("simplexsl.xml");
Init("simple.xsl");
NSUrl url = new NSUrl("file:///" + targetFilepath, false);
NSUrl readAccessUrl = new NSUrl("file:///" + Path.GetDirectoryName(targetFilepath), true);
webview.LoadFileUrl(url, readAccessUrl);
Result: white page
LoadHtmlString()
string targetFilepath = Init("simplexsl.xml");
Init("simple.xsl");
NSData documentData = NSData.FromFile(targetFilepath);
if(documentData != null && documentData.Length > 0)
{
NSString htmlString = NSString.FromData(documentData, NSStringEncoding.UTF8);
webview.LoadHtmlString(htmlString, readAccessUrl);
}
Result: content of xml is shown (without tags from xml), but styling is not applied.
NSUrl readAccessUrl = new NSUrl("file:///" + Path.GetDirectoryName(targetFilepath), true);
NSString htmlString = new NSString(File.ReadAllText(targetFilepath));
webview.LoadHtmlString(htmlString, readAccessUrl);
Result: content of xml is shown (without tags from xml), but styling is not applied.
LoadData()
string targetFilepath = Init("simplexsl.xml");
Init("simple.xsl");
NSUrl readAccessUrl = new NSUrl("file:///" + Path.GetDirectoryName(targetFilepath), true);
NSData documentData = NSData.FromFile(targetFilepath);
if(documentData != null && documentData.Length > 0)
{
webview.LoadData(documentData, "text/xml", "utf-8", readAccessUrl);
}
Result: white page
LoadRequest()
string targetFilepath = Init("simplexsl.xml");
Init("simple.xsl");
NSUrl url = new NSUrl("file:///" + targetFilepath, false);
webview.LoadRequest(new NSUrlRequest(url));
Result: white page
Different paths
var documents = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User) [0].Path;
var caches = Path.Combine (documents, "Caches");
Result: white page
var caches = Path.Combine(System.IO.Path.GetTempPath(), "www");
Directory.CreateDirectory(caches);
Result: white page
Bundle Resource
string folder = NSBundle.MainBundle.BundlePath;
string source = Path.Combine(folder, "simplexsl.xml");
webview.LoadFileUrl(new NSUrl(source,false), new NSUrl(folder, true))
Result: white page
Link
Now I loaded a html with a link in it
XML Link
Result: html page is loaded, clicking the link leads to a white page, if xsl is commented out in xml then the xml is shown without styling
Online
webview.LoadRequest(new NSUrlRequest(new NSUrl("http://www.w3schools.com/xml/simplexsl.xml")));
Result: WKWebView can show the XML file if you allow it load non https resources.
Without XSL
Comment out the following line in simplexsl.xml
<?xml-stylesheet type="text/xsl" href="simple.xsl" ?>
and using
webview.LoadFileUrl(url, readAccessUrl);
Result: content of xml is shown (without tags from xml), but styling is not applied. So it seems that there is a basepath issue, but only with XSL files?
Displaying a html file, which references a picture relatively, does work, when I use LoadFileUrl(). But with xml files there seems to be a problem. For a short test UIWebView seems to handle that better.
So how is it done correctly?
Basic setup
public override void ViewDidLoad()
{
base.ViewDidLoad();
var webview = new WKWebView(View.Bounds, new WKWebViewConfiguration());
View.AddSubview(webview);
// code here
}
private string Init(string filename)
{
string sourceFilepath = Path.Combine(NSBundle.MainBundle.BundlePath, filename);
var library = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).Replace("Documents", "Library");
var caches = Path.Combine(library, "Caches");
var targetFilepath = Path.Combine(caches, filename);
if (CopyFile(sourceFilepath, targetFilepath))
return targetFilepath;
return string.Empty;
}
private bool CopyFile(string sourceFilepath, string targetFilepath)
{
if (File.Exists(sourceFilepath))
{
File.Copy(sourceFilepath, targetFilepath, true);
return true;
}
return false;
}
targetFilepath is something like /Users/some-user/Library/Developer/CoreSimulator/Devices/8808B80D-D232-4599-B776-139409C9DDB8/data/Containers/Data/Application/BC84CFD0-A805-417C-912F-C2B07834C822/Library/Caches/simplexsl.xml
simplexsl.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="simple.xsl" ?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
simple.xsl
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
<xsl:for-each select="breakfast_menu/food">
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold">
<xsl:value-of select="name"/> -
</span>
<xsl:value-of select="price"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<p>
<xsl:value-of select="description"/>
<span style="font-style:italic">
(<xsl:value-of select="calories"/> calories per serving)
</span>
</p>
</div>
</xsl:for-each>
</body>
</html>
It would be no problem if you post your solutions in Objective-C or Swift.
I've the bad feeling, that the XSL transform is not allowed for local files (despite in the same directory) because of security concerns. If I open the file in Chrome I get
Unsafe attempt to load URL file:///C:/some/path/Projects/TestWKWebView/TestWKWebView/Resources/simple.xsl from frame with URL file:///C:/some/path/Projects/TestWKWebView/TestWKWebView/Resources/simplexsl.xml. 'file:' URLs are treated as unique security origins.
Firefox works fine. In Edge I get
XSLT8690: The system cannot locate the object specified.
Very interesting comment from here:
Interesting fact: Safari on Mac (8.0) works just fine with local XSLT, but Safari on iOS (8) simulator (and I suppose on iOS as well) I got the same error like in Chrome "Domains, protocols and ports must match.". But if I'm to implement UIWebView in the app and load XML with XSLT everything works OK.
After some research it seems that there are the following solutions:
Use UIWebView
Use a local webserver (e.g. look here)
Perhaps do the XSLT yourself with the help of libxslt (see here or here, also available as NuGet package)

Query Job Information

I was looking at the Onscreen Reference to see if there's an XML request for querying jobs. I found that there's just customer query request CustomerQueryRq and that too doesn't return the child jobs that it has.
Supposing this is how the customers & jobs centre looks like:
- Customer 1
-- Job 1
-- Job 2
-- Job 3
I was able to use CustomerQueryRq and get the details for Customer 1, but couldn't find anything for retrieving Job 1.
So my question is how do I query for a job and get the parent customer it's in? I'd really appreciate any help.
EDIT: Posting my QBXML request:
<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
<QBXMLMsgsRq onError="continueOnError">
<CustomerQueryRq requestID="1">
<FullName>Customer name</FullName>
</CustomerQueryRq>
</QBXMLMsgsRq>
</QBXML>
The Customer name has child jobs and I'd like to query those.
ICustomerQuery returns the list of Jobs along with the Customers list. There isn't a separate query object for Jobs. Each job has a customer as a parent. Hence, you can also retrieve the associated customer for the job.
Here's an example: I have a job J1 associated with a customer C1 in my company file. In the below C# code sample, I create a customer query object (using QB SDK 13.0) and iterate over the results. I get two results in the customer list( C1 and J1 ):
using QBXMLRP2Lib;
using Interop.QBFC13;
public class SDKApp
{
private QBSessionManager sessionMgr;
public SDKApp()
{
// in the class constructor - sessionMgr is a member variable
sessionMgr = new QBSessionManager();
}
public void GetData()
{
// open connection and begin session before data fetch - intentionally skipped this code
// during data fetch
IMsgSetRequest msgset = sessionMgr.CreateMsgSetRequest("US", 13, 0);
ICustomerQuery customerQuery = msgset.AppendCustomerQueryRq();
IMsgSetResponse msgRes = sessionMgr.DoRequests(msgset);
IResponseList responseList = msgRes.ResponseList;
if (responseList.Count > 0)
{
IResponse response = responseList.GetAt(0);
ICustomerRetList customerList = response.Detail as ICustomerRetList;
for (int i = 0; i <= customerList.Count - 1; i++)
{
ICustomerRet qbCustomer = customerList.GetAt(i);
string displayName = qbCustomer.Name.GetValue();
string entityType = "Customer";
if (qbCustomer.ParentRef != null)
{
entityType = "Job of " + qbCustomer.ParentRef.FullName.GetValue();
}
Console.WriteLine(displayName + " " + entityType);
}
}
// end session and close connection after data fetch - intentionally skipped this code
}
}

TwiML App unexpected end of call: Cannot find the declaration of element 'response'

I created TwiML application and set Voice request URL the web deployed ASP.NET-MVC aplication action method: http://voiceapp-001-site1.myasp.net/voice
This action method is invoked when somebody goes to the URL posted above:
public ActionResult Voice() {
Response.ContentType = "text/xml";
// put a phone number you've verified with Twilio to use as a caller ID number
string callerId = Settings.TwilioNumber;
// put your default Twilio Client name here, for when a phone number isn't given
string number = "jenny";
// get the phone number from the page request parameters, if given
if (Request["PhoneNumber"] != null) {
number = Request["PhoneNumber"];
}
// wrap the phone number or client name in the appropriate TwiML verb
// by checking if the number given has only digits and format symbols
string numberOrClient;
var m = Regex.Match(number, #"^[\d\+\-\(\) ]+$");
if (m.Success) {
numberOrClient = string.Format("<Number>{0}</Number>", number);
} else {
numberOrClient = string.Format("<Client>{0}</Client>", number);
}
ViewBag.CallerId = callerId;
ViewBag.NumberOfClient = numberOrClient;
return View();
}
The Voice view looks like:
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<dial callerid="#ViewBag.CallerId">
#Html.Raw(ViewBag.NumberOfClient)
</dial>
</response>
Then I try to make test call:
but after 13 seconds call is automatically terminated and In the error log I get:
Notification SID NOe85ffe80dfc52e81f942a7414c9f7c9c
Warning 12200 Schema validation warning
Description Cannot find the declaration of element 'response'.
But below in the Body section I can see the element response:
Hi Twilio developer evangelist here.
Can you try modifying your view to look like this instead?
<?xml version="1.0" encoding="UTF-8" ?>
<Response>
<Dial callerId="#ViewBag.CallerId">
#Html.Raw(ViewBag.NumberOfClient)
</Dial>
</Response>
Remember XML is case-sensitive, so the casing in your XML tags actually matter. Also, I would suggest using the Twilio.TwiML helper library. With that, you can get your XML generated for you with the right casing, and avoiding typos altogether.
Here's how you'd do it:
var twiml = new TwilioResponse();
var dialAttributes = new {callerId = "48326304351"};
var dial = twiml.Dial("+15555555555", dialAttributes);
return TwiML(dial);

Creating soap request with http build

Im trying to make a soap request using httpbuilder. I need to pass some authentication parameters in the head section.
My code is as follows
def String WSDL_URL = 'http://ws.tradetracker.com/soap/affiliate?wsdl'
def http = new HTTPBuilder( WSDL_URL , ContentType.TEXT )
String soapEnvelope =
"""<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap-env:Header>
<authenticate>
<customerID>id</customerID>
<passphrase>pass</passphrase>
<demo>true</demo>
</authenticate>
</soap-env:Header>
<soap12:Body>
<getConversionTransactions xmlns="xmlns':'http://schemas.xmlsoap.org/wsdl">
<affiliateSiteID>id</affiliateSiteID>
</getConversionTransactions>
</soap12:Body>
</soap12:Envelope>"""
http.request( Method.POST, ContentType.TEXT ) {
body = soapEnvelope
response.success = { resp, xml ->
String xm = xml.readLines()
println "XML was ${xm}"
def territories = new XmlSlurper().parseText(
'<?xml version="1.0" encoding="UTF-8"?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="urn:http://ws.webgains.com/aws.php" xmlns:enc="http://www.w3.org/2003/05/soap-encoding" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><env:Body xmlns:rpc="http://www.w3.org/2003/05/soap-rpc"><ns1:getFullUpdatedEarningsResponse env:encodingStyle="http://www.w3.org/2003/05/soap-encoding"><rpc:result>return</rpc:result><return enc:itemType="ns1:fullLinesArray" enc:arraySize="1" xsi:type="ns1:fullReportArray"><item xsi:type="ns1:fullLinesArray"><transactionID xsi:type="xsd:int">39367137</transactionID><affiliateID xsi:type="xsd:int">59987</affiliateID><campaignName xsi:type="xsd:string">www.tikcode.com</campaignName><campaignID xsi:type="xsd:int">136755</campaignID><date xsi:type="xsd:dateTime">2013-05-13T15:04:48</date><validationDate xsi:type="xsd:dateTime">2013-05-13T15:04:48</validationDate><delayedUntilDate xsi:type="xsd:string"></delayedUntilDate><programName xsi:type="xsd:string">Miniinthebox - US</programName><programID xsi:type="xsd:int">4611</programID><linkID xsi:type="xsd:string">95661</linkID><eventID xsi:type="xsd:int">7285</eventID><commission xsi:type="xsd:float">0.06</commission><saleValue xsi:type="xsd:float">0.8</saleValue><status xsi:type="xsd:string">confirmed</status><paymentStatus xsi:type="xsd:string">notcleared</paymentStatus><changeReason xsi:nil="true"/><clickRef xsi:nil="true"/><clickthroughTime xsi:type="xsd:dateTime">2013-05-13T14:58:33</clickthroughTime><landingPage xsi:type="xsd:string">http%3A%2F%2Fwww.lightinthebox.com%2Fes%2F%3Flitb_from%3Daffiliate_webgains</landingPage><country xsi:type="xsd:string">ES</country><referrer xsi:type="xsd:string">http%3A%2F%2Flocalhost%3A8080%2Fcom.publidirecta.widget%2Fpromocion%2FverPromocion%3Fpromocion%3D</referrer></item></return></ns1:getFullUpdatedEarningsResponse></env:Body></env:Envelope>').declareNamespace("ns1":"http://ws.webgains.com/aws.php")
println "aaaaaaaaaaaaaaaa"+ territories.Body.getFullUpdatedEarningsResponse.return.item.transactionID
}
response.failure = { resp, xml ->
println "pues peto, no se porque"+xml.readLines()
}
}
Im getting the following error and I dont have any clue wants wrong
<?xml version="1.0" encoding="UTF-8"?>, <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Body><env:Fault><env:Code><env:Value>env:Sender</env:Value></env:Code><env:Reason><env:Text>Body must be present in a SOAP envelope</env:Text></env:Reason></env:Fault></env:Body></env:Envelope>
Namespace for Envelope and its corresponding Header element is mismatching.
<soap12:Envelope> should have <soap12:Header> instead you have <soap-env:Header>. The payload becomes invalid in the header element so body becomes unreachable.
Like #dmahapatro said you have a problem in your XML. Anyway checking your code I've noted that you are using HTTPBuilder directly. Maybe you can try to use groovy-wslite (https://github.com/jwagenleitner/groovy-wslite) to make SOAP requests. It's very simple to call and process the response. There is a plugin for Grails, despite I'm not using the plugin, but the groovy-wslite directly.
BuildConfig.groovy
dependencies {
compile 'com.github.groovy-wslite:groovy-wslite:0.7.2'
runtime 'com.github.groovy-wslite:groovy-wslite:0.7.2'
}
In a Grails Service for instance:
def cnpj = "999999999906"
def clientSOAP = new SOAPClient('https://www.soawebservices.com.br/webservices/producao/cdc/cdc.asmx')
def response = clientSOAP.send (SOAPVersion.V1_2,
"""<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<PessoaJuridicaNFe xmlns="SOAWebServices">
<Credenciais>
<Email>xxxxx</Email>
<Senha>xxxxx</Senha>
</Credenciais>
<Documento>${cnpj}</Documento>
</PessoaJuridicaNFe>
</soap12:Body>
</soap12:Envelope>"""
)
//processing the response (very simple...)
Client client = new Client()
client.webServiceMsg = response.PessoaJuridicaNFeResponse.PessoaJuridicaNFeResult.Mensagem.text()
client.nome = response.PessoaJuridicaNFeResponse.PessoaJuridicaNFeResult.RazaoSocial.text()
//etc...

Resources