XML malformed fix using nodejs - node.js

I have an xml like this but i want to convert the xml into proper xml by node.js can anyone help me in this
<?xml version = 1.0 encoding = utf-8?>
<!-- xslplane.1.xml -->
<?xml-stylesheet type = text/xsl href = xslplane.1.xsl ?>
<plane>
<year> 1977 </year>
<make> Cessna </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
</plane>
I want XML like this with all the possible quotations
<?xml version = "1.0" encoding = "utf-8"?>
<!-- xslplane.1.xml -->
<?xml-stylesheet type = "text/xsl" href = "xslplane.1.xsl" ?>
<plane>
<year> 1977 </year>
<make> Cessna </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
</plane>

You can try using xml2js to convert your malformed xml to JSON and use it again to convert to xml. Try the following code.
let xml2js = require('xml2js');
var xml = "<hi>Hello xml2js!</hi>";
xml2js.parseString(xml, function (err, result) {
console.dir(result);
var builder = new xml2js.Builder();
var xml = builder.buildObject(result);
console.log(xml)
});
Update : Direct File read
var parser = new xml2js.Parser();
fs.readFile(__dirname + '/foo.xml', function(err, data) {
parser.parseString(data, function (err, result) {
console.dir(result);
console.log('Done');
var builder = new xml2js.Builder();
var xml = builder.buildObject(result);
console.log(xml)
});
});

Related

Issue while converting xml to json, and then back to xml

I'm facing an issue when converting XML to JSON and then JSON to XML.
I'm using this xml-js npm library.
data.xml
<?xml version="1.0" encoding="UTF-8"?>
<property name="DESCRIPTION" value="Group 1 & , " , <"/>
test.js
const convert = require('xml-js');
const fs = require('fs');
const xml = fs.readFileSync('data.xml',).toString();
const result = convert.xml2json(xml, {compact: false, spaces: 2});
const output = convert.json2xml(result,{compact: false, spaces: 2});
fs.writeFileSync('output.xml', output);
output.xml
<?xml version="1.0" encoding="UTF-8"?>
<property name="DESCRIPTION" value="Group 1 & , " , <"/>
I was expecting to get the below result in output.xml
expected output.xml
<?xml version="1.0" encoding="UTF-8"?>
<property name="DESCRIPTION" value="Group 1 & , " , <"/>
Any idea why I'm getting that data on converting from JSON to XML.
I was able to get the problem fixed by using attributeValueFn.
const convert = require('xml-js');
const fs = require('fs');
const xml = fs.readFileSync('data.xml',).toString();
const result = convert.xml2json(xml, {compact: false, spaces: 2,
attributeValueFn: function(value) {
return value.replace(/&/g,'AMPERSAND_CHARACTER');
}
});
console.log('JSON : ' + result);
const output = convert.json2xml(result,{compact: false, spaces: 2,
attributeValueFn: function(value) {
return value.replace(/AMPERSAND_CHARACTER/g, '&')
.replace(/</g, '<');
}
});
fs.writeFileSync('output.xml', output);

How to append element after particular element in nodejs

My .XMl is
<?xml version="1.0" encoding="utf-8"?>
<data>
<shell id="TX-alg1-title">Lesson 2.1</shell>
<options id="parent">
<option id="TX-alg1">TX16E_ISE_0005</option>
<option id="TX-alg1-CID">9780353053</option>
</options>
</data>
I wanted to add another shell tag after shell tag previously present in xml.
Expected O/p
<?xml version="1.0" encoding="utf-8"?>
<data>
<shell id="TX-alg1-title">Lesson 2.1</shell>
<shell id="CA-int1-title">Lesson 2.1</shell>
<options id="parent">
<option id="TX-alg1">TX16E_ISE_0005</option>
<option id="TX-alg1-CID">9780353053</option>
</options>
</data>
I am reading my .XML file in app.js as
fs.readFile( './dlo_custom_en-US.xml', function(err, data) {
});
Please advise how to append shell tag after already present shell tag in nodejs.
question is almost similar Regex match text between tags
node is noting except javascript at server side. almost all programming languages have regexp to find patterns. here is simplest solution but you should to study more about regexp
fs.readFile( './dlo_custom_en-US.xml', function(err, data) {
data.replace(/\<shell(.)*\<\/shell>/, "new replacement here")
});
***** updated *****
from JavaScript: How can I insert a string at a specific index
var fs =require('fs')
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
fs.readFile( './dlo_custom_en-US.xml',"utf8", function(err, data) {
if(err) return
var index = data.lastIndexOf('</shell>')+8
console.log(index)
var data= data.splice(index,0, 'newwwwwwwwwww')
console.log(data)
fs.writeFile('./new.xml',data,(err, done)=>{
if(err) return
console.log(err, done)
})
});

How to hide "Attachment" menu for specific model and group in Odoo?

I want to hide "Attachment(s)" menu in the form view for specific group and model/object in odoo 8. How can i do it?
I do not have idea about hide attachment menu but can restrict to attach via this js code:
odoo.define('module_name', function(require) {
"use strict";
var core = require('web.core');
var data = require('web.data');
var framework = require('web.framework');
var sideWidget = require('web.Sidebar');
var Model = require('web.Model');
var Dialog = require('web.Dialog');
var _t = core._t;
var QWeb = core.qweb;
var sidebar = sideWidget.include({
redraw: function() {
var self = this;
this._super.apply(this, arguments);
if (this.getParent()) {
var view = this.getParent();
if (this.getParent().dataset.model != "there which model you do not want attach files") {
this.$('.o_sidebar_add_attachment .o_form_binary_form').change(this.on_attachment_changed);
}
}
},
});
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data>
<template id="assets_backend_niwe" name="alfresco_odoo assets" inherit_id="web.assets_backend">
<xpath expr="." position="inside">
<script type="text/javascript" src="file location"/>
</xpath>
</template>
</data>
</odoo>
Save it separate file and add this js file it to assets backend.

Reference Error: $ is not defined -while loading the DZI xml file -OpenSeaDragon

Below is the code snippet that iam using to load and display DZI xml files. I am getting reference error:$ is not defined.
var dziFilesUrl = '//DZI//dzc_output_files//';
// Change this to the contents of the .dzi file from your server.
var dziData = '<?xml version="1.0" encoding="utf-8"?><Collection MaxLevel="8" TileSize="256" Format="jpg" NextItemId="1" xmlns="http://schemas.microsoft.com/deepzoom/2008"><Items><I Id="0" N="0" Source="dzc_output_images/worldmap.xml"><Size Width="5000" Height="3752" /><Viewport Width="1" X="-0" Y="-0" /></I></Items></Collection>';
// This converts the XML into a DZI tile source specification object that OpenSeadragon understands.
var tileSourceFromData = function (data, filesUrl) {
var $xml = $($.parseXML(data));
var $image = $xml.find('Image');
var $size = $xml.find('Size');
var dzi = {
Image: {
xmlns: $image.attr('xmlns'),
Url: filesUrl,
Format: $image.attr('Format'),
Overlap: $image.attr('Overlap'),
TileSize: $image.attr('TileSize'),
Size: {
Height: $size.attr('Height'),
Width: $size.attr('Width')
}
}
};
console.log(dzi);
return dzi;
};
// This creates the actual viewer.
var viewer = OpenSeadragon({
id: 'openseadragon1',
prefixUrl: '//DZI/',
tileSources: tileSourceFromData(dziData, dziFilesUrl)
});
Please let me know what I need to correct.
I am using latest OpenSeaDragon Version 2.3.0
You need to include jQuery. More discussion here:
https://github.com/openseadragon/openseadragon/issues/1255

How to get attribute value of node in xml using xpath in javascript

Hi I am trying to get the user profile properties from sharepoint on client side with javascript.But I am not getting the value of nodes in xml.
How to get them. the xml will look like as:
How to get attribute value of node in xml using xpath
Here I want to get the value which is between <name> tags <Name>AccountName</Name> and between Name tags
want to get the value = abc what will be the xpath expression
Please help
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetUserProfileByNameResponse xmlns="http://microsoft.com/webservices/SharePointPortalServer/UserProfileService">
<GetUserProfileByNameResult>
<Pro pertyData>
<IsPrivacyChanged>false</IsPrivacyChanged>
<IsValueChanged>false</IsValueChanged>
<Name>UserProfile_GUID</N ame>
<Privacy>NotSet</Privacy>
<Values>
<ValueData>
<Value xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">8ed84415-7330-4857-a7d2- d797d71c439f
</Value>
</ValueData>
</Values>
</PropertyData>
<PropertyData>
<IsPrivacyChanged>false</IsPrivacyChanged>
<Is ValueChanged>false</IsValueChanged>
<Name>AccountName</Name>
<Privacy>NotSet</Privacy>
<Values>
<ValueData>
<Value xsi:type="xsd:string">abc
</Value>
</ValueData>
</Values>
</PropertyData>
</GetUserProfileByNameResult>
</GetUserProfileByNameResponse>
</ soap:Body>
</soap:Envelope>
Please help me in this.
var propertyData = $(responseXML).find("PropertyData").filter(function(e){
return $(this).find("Name").text() == "AccountName";
});
var value = propertyData.length > 0 ? propertyData.find('Value').text() : '';
Since you are trying to retrieve user profile via SharePoint Web Services I would recommend to utilize SPServices library, it hides (almost)all the intricacies when working with SharePoint Web Services from JavaScript. The following example demonstrates how to retrieve user profile using GetUserProfileByName method and process the results:
function getUserProfile(accountName,completeFn) {
var userInfo = {};
$().SPServices({
AccountName: accountName,
operation: 'GetUserProfileByName',
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("PropertyData").each(function() {
userInfo[$(this).find("Name").text()] = $(this).find("Value").text();
});
completeFn(userInfo);
}
});
}
var loginName = 'i:0#.f|membership|username#contoso.onmicrosoft.com';
getUserProfile(loginName,function(info){
console.log(info);
});
You have to traverse through the xml nodes returned from the SPServices. I have written a function for getting the desired user profile property.
function getUPValue(x, p) {
var thisValue = $(x).SPFilterNode("PropertyData").filter(function() {
return $(this).find("Name").text() == p;
}).find("Values").text();
return thisValue;
}
Further to query the user property you just need to call like below,
getUPValue(xData.responseXML, "WorkEmail");
These article provides a detail overview of it over here

Resources