Remove parent nodes if contains tag - domdocument

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();

Related

Parse using XMLDictionary

I am using 'XMLDictionary' to parse xml. In one case I am getting the following dictionary(after converting NSData response to NSDictionary using 'dictionaryWithXMLData')
{
"__name" = "soap:Envelope";
"_xmlns:soap" = "http://schemas.xmlsoap.org/soap/envelope/";
"_xmlns:xsd" = "http://www.w3.org/2001/XMLSchema";
"_xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance";
"soap:Body" = {
GetPublicationsListResponse = {
GetPublicationsListResult = 0;
"_xmlns" = "http://questbase.org/";
publicationsList = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<publications>\n <publication>\n <pin>4533-1490-8280</pin>\n <title>Unsecure Assessment</title>\n <isSecure>0</isSecure>\n </publication>\n <publication>\n <pin>5123-4751-0595</pin>\n <title>Secure Assessment</title>\n <isSecure>1</isSecure>\n </publication>\n</publications>";
studentID = "4795e7fc-5c98-4ec4-a155-5f719f14ef3e";
};
};
}
Here, object for key publicationList is in xml and I am stuck trying to convert it into NSDictionary. Plz help.
Original xml request made was in the form:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<SecurityHeader xmlns="http://questbase.org/">
<Password>string</Password>
</SecurityHeader>
</soap:Header>
<soap:Body>
<GetPublicationsList xmlns="http://questbase.org/">
<accountName>string</accountName>
<userName>string</userName>
<password>string</password>
<ipAddress>string</ipAddress>
<userAgent>string</userAgent>
</GetPublicationsList>
</soap:Body>
</soap:Envelope>
and the response is as follows:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetPublicationsListResponse xmlns="http://questbase.org/">
<GetPublicationsListResult>int</GetPublicationsListResult>
<studentID>guid</studentID>
<publicationsList>string</publicationsList>
</GetPublicationsListResponse>
</soap:Body>
</soap:Envelope>

Pass parameter from a URL to a XSL stylesheet

I just spent the past couple of days digging into the messages looking for a way to pass a parameter from an URL to a XSL stylesheet.
for example, I have a current url like:
http://localhost/blocableau/data/base_bloc/blocableau3x.xml?95.2
and I want to just select the value after the ? like the 95.2 in this example, and put it in the variable var_massif.
I tried the following code with javascript for test the value substring(1) but with xsl it didn't work.
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes" />
<!-- recherche des cotations par Massif selon une variable -->
<xsl:key name="byMassif" match="bloc" use="Massif" />
<xsl:template match="BLOCS">
<script>var requete = location.search.substring(1);
mavariable=requete;alert(mavariable);x=mavariable</script>
<xsl:variable name="var_massif"><xsl:value-of select="95.2" /></xsl:variable>
<span>Ma variable xsl est : <xsl:value-of select="$var_massif"/></span>
<div style="position:relative; top:0px;left:10px;font-family: Arial, 'Helvetica Neue', 'Helvetica, sans-serif'; font-size:12px;z-index:1;">
<!-- genere un id pour chaque valeur de cotation et mise en forme -->
<xsl:for-each select="bloc[generate-id() = generate-id(key('byMassif', $var_massif)[1])]" >
<xsl:sort select="Massif" />
I assume you are loading a XML which uses a XSL processing instruction to transform the file:
<?xml-stylesheet ... ?>
You would need to read the URL and extract the query string. Unfortunately it is not automatically mapped. The only way to do that would be using document-uri(/) but it's XSLT 2.0 and not supported in browsers.
In XSLT 1.0 you would have to direct your HTTP request not to the XML file you want to process, but to a script which will load your XML and XSLT using the XSLTProcessor. Then you could pass the query-string as a parameter to the processor:
var var_massif = location.search.substring(1); // gets the string and removes the `?`
var processor = new XSLTProcessor(); // starts the XSL processor
processor.setParameter(null, "var_massif", var_massif); // sets parameter
... // load XSL, XML and transformToDocument
Inside your XSLT stylesheet you should have a global parameter variable:
<xsl:param name="var_massif" />
Which you will then be able to read with $var_massif.
UPDATE Here is a step-by-step example using JQuery:
I'm using this reduced stylesheet, just to show you how to get the parameter. It's in a file I called stylesheet.xsl:
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes" />
<xsl:param name="var_massif" />
<xsl:template match="BLOCS">
<span>Ma variable xsl est : <xsl:value-of select="$var_massif" /></span>
</xsl:template>
</xsl:stylesheet>
And this input (blocableau3x.xml) in the same directory:
<BLOCS>
<bloc>
<Massif></Massif>
</bloc>
</BLOCS>
Now create this HTML file (blocableau3x.html) also in the same directory:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script>
$( document ).ready(function() {
var var_massif = location.search.substring(1); // gets the string and removes the `?`
var body = $("body")[0]; // gets the body element where the result will be inserted
if (var_massif) {
var processor = new XSLTProcessor(); // starts the XSL processor
processor.setParameter(null, "var_massif", var_massif);
var source;
var xslReq = $.get("stylesheet.xsl", function (data) { // loads the stylesheet
processor.importStylesheet(data);
});
var xmlReq = $.get("blocableau3x.xml", function (data) { // loads the xml
source = data;
});
$.when(xslReq, xmlReq).done(function () { // waits both to load
var result = processor.transformToDocument(source); // transforms document
body.appendChild(result.documentElement); // adds result as child of body element
});
} else {
body.html("<h1>Missing query string</h1>"); // in case there is no query string
}
});
</script>
<html>
<body></body>
</html>
Instead of calling your XML file in the URL, call the HTML file. When it loads, it will load the XSL file and the XML file, and use the XSL processor to process the file. It will be able to read the query parameter and pass it as a XSL global parameter, which you can read in your XSLT file.

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...

Breadcrumbs Symfony

I'm using an old version of symfony 1.0.11
slot('breadcrumbs');
include_component('page','breadcrumbs',array('past_pages'=>array(
'/module/action/parameter/value'=>'Home ')));
end_slot();
The problem with this code is that parameter and value do not get passed, so If i click on home i get /module/action but the parameters are not being passed. Any suggestions?
Thanks.
There is also a way automatically set the breadcrumbs this is in the breadcrumbs actions:
// Get the full path without get parameters
$fullPath = $request->getPathInfo();
// get the get parameters
$urlParams = $request->getGetParameters();
// set get parameters as string for url
$this->extend = "";
foreach ($urlParams as $key => $urlParam) {
if (empty($this->extend)) {
$this->extend = "?";
}
this->extend .= $key."=".$urlParam;
}
// Get the URL path and Explode by /
$paths = explode('/', $fullPath);;
$this->paths = $paths;
then in the component itself, you can foreach through the paths and if empty just continue. And always give the GET variables with the link if the browser has some.
Home
<?php foreach($paths as $path):
if(empty($path))
continue;
if(empty($fullPath))
$fullPath = "";
$fullPath .= "/".$path.$extend;
$path = str_replace("-", " ", $path);
?>
<?php if(key($paths->getRawValue()) != (count($paths)-1)): ?>
<?php echo ucwords($path); ?>
<?php else: ?>
<span><?php echo ucwords($path); ?></span>
<?php endif; ?>
This way you never have to set your breadcrumbs if you have a correct url structure.
the way i fixed it is
include_component('page','breadcrumbs',array('past_pages'=>array(
'/module/action?parameter=value'=>'Home ')));

how to extract values from an xml tree using 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.

Resources