fast-xml-parser: Build xml with attributes and child elements from json
I'm using fast-xml-parser to create xml documents from json. In the examples they show how to create an element with attributes
const jsOrderedObj = [
{
"?textinfo": [
{
"#text": ""
}
],
":@": {
"@_whitespace": true,
"@_is": true,
"@_allowed": true
}
}
];
const options = {
ignoreAttributes: false,
preserveOrder: true,
allowBooleanAttributes: true,
suppressBooleanAttributes: true
};
const builder = new XMLBuilder(options);
const output = builder.build(result);
result:
<?textinfo whitespace is allowed?>
And examples of how to create an XML document with child elements:
const xmlData = {
'foo': {
'bar': 'data',
'bar2': 'data2',
'bar3': 'data3',
'bar4': 'data4',
}
}
const builder = new XMLBuilder({});
const output = builder.build(xmlData);
result:
<foo><bar>data</bar><bar2>data2</bar2><bar3>data3</bar3><bar4>data4</bar4></foo>
Now my question is, how should I define my json, to get both attributes and child elements in my xml, like this:
<foo whitespace is allowed><bar>data</bar><bar2>data2</bar2><bar3>data3</bar3><bar4>data4</bar4></foo>
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
MarkLogic server-side JavaScript and XQuery
I am just starting using NoSQL MarkLogic DB and trying to choose for me the best query language to learn and use in future. On server side MarkLogic provides the possibility to use JavaScript API or XQuery API.
I want to receive an advice. Which language is better to concentrate on and learn? JavaScript or XQuery?
- Popover in chrome extension using js
-
How to convert String having key=value pairs to Json
myString =
{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00};
I want to convert it to the following string.
{"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};
How can I do it in java?
-
Fetch doesn't retrive data
I am currently building a login form which will be using a restAPI for the registration/Auth but I'm receiving a 401 error when using fetch to test the retrieved data.
console.log(fetch('http://localhost:5000/users/'), { method: 'get', headers: { 'Content-Type': 'application/json' }, })
.then(res => res.json()) .then(json => console.log(json))</code>
-
NextJS: Error serializing `.data.data` returned from `getServerSideProps`
I'm new to NextJS. I'm working on a simple page in which I need to retrieve data from my backend app. My backend app is a totally separate app written in go. My undestanding is that I must use
getServerSideProps
to get data from the server on load, so I've got the following:myProject/pages/category/new.js
:export default function AddNewCategory(data) { ... } export const getServerSideProps = async () => { const data = await getAllCategories(); console.log(await data) return { props: { data: { data } } }; };
myProject/api/category.js
:import axios from "axios"; // getAllCategories returns a list of all active categories export const getAllCategories = async() => { axios.get("http://127.0.0.1:8080/api/v1/categories") .then(function (response) { console.log(response.data) return response.data; }) .catch(error => { console.error("error") console.log(error) }) }
As you can see I've got a print statement in
getAllCategories
which prints:{ data: [ { id: 1, name: 'Pop', slug: 'pop', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:00-04:00', updated_at: '2022-05-03T19:50:00-04:00', deleted_at: null }, { id: 3, name: 'Pop 2', slug: 'pop-2', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:24-04:00', updated_at: '2022-05-03T19:50:24-04:00', deleted_at: null } ] }
yet I'm getting the following error:
error - Error: Error serializing
.data.data
returned fromgetServerSideProps
in "/category/new". Reason:undefined
cannot be serialized as JSON. Please usenull
or omit this value.I saw around that I should try to convert the data to string and then back to json:
return { props: { data: JSON.parse(JSON.stringify(data)) } };
but when I do this I'm getting a different error:
error - SyntaxError: Unexpected token u in JSON at position 0
I'm using
next@12.1.5
Any idea what's going on?
-
Java - Update Elements in Large XML Files
I work with very large XML datasets (1 GB+) and need to backtrack and update specific elements per node, depending on the values of other elements that follow.
For example, in this record/node:
<user> <role>Associate</role> <team>Hufflepuff</team> <experience>7</experience> </user>
Since "experience" is greater than 5 years, the role needs to be updated from "Associate" to "Senior."
I would like to avoid loading the entire file into memory via the DOM.
Ideally, I would process each single "user" in the XML and append the data to a new XML file one at a time. I started off by processing in a stream using StAX, but I don't know how to transform each XMLEventWriter event content into a useable DOM document that writes to an XML file and clears from memory afterwards.
If the description is unclear in any way, please let me know. Any help on this will be greatly appreciated.
Thanks.
-
cant read field in xml section
Using python I got to the correct iteration of the XML (forecast) section, but one child field I cant seem to be able to read here is the section from the XML
<forecast> <fcst_time_from>2022-05-04T16:00:00Z</fcst_time_from> <fcst_time_to>2022-05-04T20:00:00Z</fcst_time_to> <change_indicator>FM</change_indicator> <wind_dir_degrees>110</wind_dir_degrees> <wind_speed_kt>6</wind_speed_kt> <visibility_statute_mi>6.21</visibility_statute_mi> <sky_condition sky_cover="SCT" cloud_base_ft_agl="4500"/> <sky_condition sky_cover="SCT" cloud_base_ft_agl="25000"/> </forecast>
I can get every field except
<sky_condition sky_cover="SCT" cloud_base_ft_agl="25000"/>
here is the code where I pull the fields
if startTime_new <= Cur_Date_UTC <= EndTime_new: #Cil2 = (l.find('sky_cover')).text wDir = (l.find('wind_dir_degrees')).text wSpd = (l.find('wind_speed_kt')).text vis = (l.find('visibility_statute_mi')).text Cil = (l.find('sky_condition')).text print(wDir) print(wSpd) print(vis) print(Cil) print(l)
The answer given did work in a comand window but I am using beautifulsoup to get the XML . I tried to import from datetime import datetime however Cil = [x.get('sky_cover') for x in elt.findall('sky_condition')] did not work
here is my full code
from bs4 import BeautifulSoup as bs import requests import pytz from datetime import datetime #pirip=False def SetDateTimes(): utc_time = datetime.now(pytz.utc) Cur_Date_UTC = utc_time.strftime("%d/%m/%y %H:%M:%S") return Cur_Date_UTC def FixDateTime(workingTime): workingTime = workingTime.replace('T', ' ') workingTime = workingTime.replace('Z', '') format = "%Y-%m-%d %H:%M:%S" dt_object = datetime.strptime(workingTime, format) day_st = dt_object.strftime("%d") month_st = dt_object.strftime("%m") year_st = dt_object.strftime("%y") time_st = dt_object.strftime("%H:%M:%S") workingTime = day_st + '/' + month_st + '/' + year_st + ' ' + time_st return workingTime def GetTAF3(): USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36" url = 'https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=tafs&requestType=retrieve&format=xml&hoursBeforeNow=3&timeType=issue&mostRecent=true&stationString=KEWR' session = requests.Session() session.headers['User-Agent'] = USER_AGENT html = session.get(url) soup = bs(html.text, 'html.parser') taf = soup.find_all("forecast") for l in soup.findAll('forecast'): startTime = l.find('fcst_time_from').text EndTime = (l.find('fcst_time_to')).text #print(startTime) startTime_new = FixDateTime(startTime) #print(startTime_new) #print(EndTime) EndTime_new = FixDateTime(EndTime) #print(EndTime_new) #break if startTime_new <= Cur_Date_UTC <= EndTime_new: #Cil2 = (l.find('sky_cover')).text print(l) wDir = (l.find('wind_dir_degrees')).text wSpd = (l.find('wind_speed_kt')).text vis = (l.find('visibility_statute_mi')).text Cil = (l.find('sky_condition')) print(wDir) print(wSpd) print(vis) print(Cil) print(l) if 'OVC' in Cil: print("OVC Found") pirip = True else: print('No PIRIP') if float(vis) < 5: print("pirip for vis") pirip = True else: print('No PIRIP') Cur_Date_UTC = SetDateTimes() GetTAF3() #print(pirip)
-
How can I use Continue in a choose statement in xslt
I want to continue to check for other if statements if the first one is met. From what I read, Choose statement does not have this functionality like other languages do. One post suggested to just run multiple if statements but this is not working. After the first if statement is met it stops there, I want it to keep running.
How can I achieve this? This is my code:
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="root"> { "entityList": [ <xsl:for-each select="//entityList"> { "notes":"<xsl:call-template name="replace"> <xsl:with-param name="text" select="./Notes"/> </xsl:call-template>", } <xsl:if test="position() != last()">,</xsl:if> </xsl:for-each> ] } </xsl:template> <xsl:template name="replace"> <xsl:param name="text"/> <xsl:param name="searchString">"</xsl:param> <xsl:param name="replaceString">\"</xsl:param> <xsl:param name="searchStringSpace">	</xsl:param> <xsl:param name="searchStringBackslash">\</xsl:param> <xsl:if test="contains($text,$searchString)"> <xsl:value-of select="replace(./Notes,'"','\\"')"/> </xsl:if> <xsl:if test="contains($text,$searchStringSpace)"> <xsl:value-of select="replace(./Notes,'	','\\t')"/> </xsl:if> </xsl:template> </xsl:stylesheet>
<root> <totalRecords>429</totalRecords> <offset>0</offset> <entityList> <Notes>Dear Deans, Chairs and "Directors,There was a 	ANDOR question about scheduling Mac Hall Auditorium,for regular classes and policy/procedure around it.,Mac Hall Auditorium was intended to be available as a,regular classroom. That is why the seats have built-in mini,desks.,Your programs are welcome to schedule classes in,Mac Auditorium - you can request it when submitting your,course schedules for the Semester or through the Schedule,Change Request Form.,There are, however, some conditions:,1)faculty members who teach in Mac Auditorium should,anticipate that their class may be displaced if the,University-wide function (president?s address, a conference,,etc.) is scheduled at the time of their class. It would be,up to the faculty to either reschedule that,class meeting for a different time, find another room/space,or substitute the class meeting with an alternative activity,There is no easy way to inform faculty about the upcoming,events, so they would have to watch University Calendar to,determine when their classes might be affected.,2)Mac Hall will be unavailable for scheduling regular,courses during evening hours (6-10 pm) ? that time will be,set aside for Pegasus Players practices.,Natalia F. Blank, Ph.D. 2/17/21</Notes> </entityList> <totalPages>1</totalPages> <page>0</page> <status>success</status> </root>
-
CDN Script Fast-XML-Parser Postman
I want to use fast-xml-parser to validate a SOAP response from a Postman request. Based on various articles, I implemented fetch cdn and put it in a variable method.
So this is my script, postman will call the cdn endpoint to get the fast-xml-parser package: https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/4.0.7/fxparser.js
pm.test("Validate XML", function () { pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/fast-xml-parser/4.0.7/fxparser.js", (error, res) => { if (error || res.code !== 200) { pm.expect.fail('Could not load external library');} const fastxmlvalidator = res.text(); console.log(fastxmlvalidator) console.log(fastxmlvalidator.XMLValidator) const result = fastxmlvalidator.XMLValidator.validate(pm.response.text(), { allowBooleanAttributes: true }); console.log(result) }); })
And store it in fastxmlvalidator constant. Now if I console log it, postman will return all the content stored in that cdn. And when I tried to use the constructor, it returned an "undefined". Hence, I cannot retrieve the function validate from it.
Here's my code in VSCode: I set the package in the fastxmlvalidator, have a sample SOAP in "XMLdata" and execute it as follow:
const fastxmlvalidator = require("fast-xml-parser"); console.log(fastxmlvalidator) const XMLdata = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"+ " <SOAP-ENV:Header/>"+ " <SOAP-ENV:Body>"+ " <Message xmlns=\"http://schemas.com.au/message/Message.xsd\">"+ " <Control>"+ " <Environment>DEV</Environment>"+ " </Control>"+ " </Message>"+ " </SOAP-ENV:Body>"+ "</SOAP-ENV:Envelope>" const result = fastxmlvalidator.XMLValidator.validate(XMLdata, { allowBooleanAttributes: true }); console.log(result)
It should return a boolean of true, which means it's a valid XML.
Any suggestions would be much appreciated it!
-
The Website reports a validation error, but the code does not
I am using the fast-xml-parser, and it trying to write a few test cases, I get a failure on some plain text from the Javascript code. However, access the site's online webpage to try the validator, returns an error.
My XML check
import * as XmlLib from 'fast-xml-parser'; class XmlWrapper { public static IsXML(XML: string): boolean | never { try { const XmlParser: XmlLib.XMLParser = new XmlLib.XMLParser({ allowBooleanAttributes: true }); const _Result = XmlParser.parse(XML); // Just using the validate directly has the same issue // const _Result = XmlLib.XMLValidator.validate(XML, { allowBooleanAttributes: true }); } } catch (Exception) { console.log(Exception); throw new Error('Bad XML'); } return true; } }
My test cases are fairly simple:
import { XmlWrapper } from './xml-wrapper'; describe('XmlWrapper', () => { it('should be defined', () => { expect(new XmlWrapper()).toBeDefined(); }); it.each([ ['undefined', undefined], ['null', null], ['empty string', ''], ['ABC', 'ABC'], ['just <?xml starting tag', '<?xml'], ])('should throw an exception when getting %s which is an invalid value.', (_Text, Value) => { expect(() => { XmlWrapper.IsXML(Value); }).toThrowError('Bad XML'); });
All the tests pass correctly, except the ABC field.
FAIL src/library/wrappers/xml-wrapper.spec.ts (7.492 s) XmlWrapper √ should throw an exception when getting undefined which is an invalid value. (7 ms) √ should throw an exception when getting null which is an invalid value. (3 ms) √ should throw an exception when getting empty string which is an invalid value. (3 ms) × should throw an exception when getting ABC which is an invalid value. (4 ms) √ should throw an exception when getting just <?xml starting tag which is an invalid value. (5 ms) ● XmlWrapper › should throw an exception when getting ABC which is an invalid value. expect(received).toThrowError(expected) Expected substring: "Bad XML" Received function did not throw
However, using the fast-xml-parser webpage with just ABC on the left, and then Validate, works.