Click here to Skip to main content
15,894,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using angularjs http to get an xml from the server, i am using node module xml2json to convert it to a json object. I get the document returned properly but it doesn't look right because it has html tags in the xml document. If anyone knows how to convert the returned json properly that would be great.
JavaScript
var x2js = new X2JS();
var dom = x2js.xml_str2json(escapchr);

XML
<my_data>
    <p class="justify">
        El Content Tour 2015 Distributors 
    </p>
</my_data>

I am still trying to figure this computer programming stuff out, i have only been coding a few months, so please excuse my bad code and kind of dumb questions, but if anyone knows how to parse the json or xml to html, i will be very grateful.
Posted
Updated 29-Oct-15 23:39pm
v3
Comments
George Jonsson 30-Oct-15 5:40am    
Do you have control over the returned XML file? Can you make changes to it?
arun1904 30-Oct-15 6:41am    
no we can't control that xml file, data cames from server.
here is the sample xml content, which contains almost 3000 lines
<pre lang="xml"><notas>
<copete>Editorial</copete>
<titulo>grande</titulo>
<seccion>Opinion</seccion>
<cuerpo>
<p class="rtejustify">
El
<strong>
<em> Foro Tour 2015
</em>
</strong> en en la hermosa ciudad de Oaxaca.
</p>
</cuerpo>
</notas>
</pre>

1 solution

Your root problem is that the XML data you get from the server is not a valid XML document. Basically you cannot have the character < inside an XML element if it is not an XML node.

This break of the XML format causes any standard XML to JSON converter to fail.

You do have a few options that you can consider:

1. Wrap the HTML code in CDATA[^]
This is the way it should have been delivered from the server
XML
<notas>
    <copete>Editorial</copete>
    <titulo>grande</titulo>
    <seccion>Opinion</seccion>
    <cuerpo>
        <![CDATA[
            <p class="rtejustify">
            El
            
             Foro Tour 2015
            
             en en la hermosa ciudad de Oaxaca.
            </p>
        ]]>
    </cuerpo>
</notas>

The data within the CDATA brackets will not be parsed and just treated as an element value.
You could insert the CDATA wrapper yourself when you receive the XML data from the server.
This will only be feasible if you have a limited number of HTML tags to consider.Otherwise you have to write a parser for the HTML tags as well.
It will also work if there is only a limited number of XML nodes that contains HTML data. For example, <cuerpo> will always contain HTML if it exists.

2. Write your own XML to JSON converter
You will still have the problem to load the XML data directly into XmlDocument or XDocument, so you might have to treat the XML data as pure text.
Then you have to do your own parsing of the text.
You can for example use regular expressions to find a start node.
<[a-z][a-z0-9_]*>

Then you can insert a slash as the second character, and you have the end node.
Cut out the block, including the XML tags, and use XElement, for example, to read the text.
If it succeeds you have a valid XML node to add to an XDocument.
If it fails you can check if you have HTML code within the block.
If so, you can wrap the data inside CDATA.
When you have a valid XML document, you can convert it to JSON.

You can also convert each node directly to JSON one by one.

This is not particularly easy to start with as a newbie, so hopefully you can use option 1.

Or maybe someone else has a better solution that is easier to implement.

[UPDATE]
Working example
HTML
<!DOCTYPE html>
<html>
	<head>
	</head>
	
	<body>
		<div class="cuerpo">
		</div>

		<script src="xml2json.js"></script>
		<script type="text/javascript">
			var xmlData = '<notas><banner>No</banner>\
				<bannerFuente></bannerFuente>\
				<bannerURL></bannerURL> \
				<copete>Editorial</copete> \
				<titulo>Se armó en grande</titulo> \
				<seccion>Opinión</seccion> \
				<resumen>El Foro Infochannel Tour 2015 concluyó y agradecemos la confianza y respuesta de los canales convocados; la disponibilidad y esfuerzo de cada uno de los representantes de las marcas y empresas patrocinadoras que nos acompañaron, y también la labor del equipo humano del semanario</resumen> \
				<cuerpo> \
<![CDATA[ \
<p class="rtejustify"><img alt="" src="Portada_Rodrigo_de_Burgosart.png" style="width: 300px; height: 257px; display: block; margin-left: auto; margin-right: auto;" /></p>\
<br />\
<a href="http://www.forbes.com/sites/louiscolumbus/2015/01/24/roundup-of-cloud-computing-forecasts-and-market-estimates-2015/" target="_blank">Goldman Sachs</a>\
<p class="rtejustify">El <strong><em>Foro Infochannel Tour 2015</em></strong> concluyó en días pasados en la hermosa ciudad de Oaxaca, Oaxaca. El escenario para concluir el recorrido no pudo ser mejor. <strong>Distribuidores </strong>de los cientos de municipios que conforman la entidad acudieron y, generosos, nos obsequiaron a organizadores y patrocinadores con su interés, posturas comerciales y puntos de vista.</p>\
<p class="rtejustify">Algunos de los asistentes viajaron por más de 10 horas para participar en el evento, de la costa a la capital del estado, agradecieron el interés de marcas como <strong>Aspel, TrippLite, Contpaqi, Toshiba, Provision ISR, Belkin-Linksys, Ghia, Plantronics, BenQ, PCH, Grupo CVA, Kingston Technology</strong>, entre otras, de acudir a la plaza a reclutar socios de negocio, formarlos y presentar a los ejecutivos que día a día, pueden apoyarlos a generar márgenes y proponer soluciones tecnológicas y de servicios a sus clientes.</p>\
<p class="rtejustify">Como organizador, <em>Infochannel </em>se enorgullece este año de los resultados totales de la gira: entramos en contacto directo con cerca de mil 600 distribuidores de todas las regiones del país, estuvimos presentes en 11 plazas donde se capacitaron a más de 430 asistentes en cursos de venta y técnicos para la <strong>comercialización de soluciones contables, de impresión, señalización digital y nuevos negocios</strong> basados en videoproyección, monitores de propósito específico, servicios administrados de impresión y seguridad, entre otros.</p>\
<p class="rtejustify">Infinitamente agradecemos la confianza y respuesta de los canales convocados; la disponibilidad y esfuerzo de cada uno de los representantes de las marcas y empresas patrocinadoras que nos acompañaron, y también la labor del equipo humano del semanario.</p>\
<p class="rtejustify">Para los fabricantes y mayoristas que apoyaron la gira y para el propio <em>Infochannel,</em> es claro que las relaciones estrechas que el Tour nos permite establecer con los distribuidores son un activo clave; hace más fluida y efectiva la comunicación, ya que existe mayor voluntad de entendimiento y utilizamos un lenguaje común, además de que sabemos con quién hablamos, y le ofrecemos soluciones a la medida de sus necesidades.</p>\
]]>\
				</cuerpo>\
			</notas>';
			
			var x2js = new X2JS();
			var jsonData = x2js.xml_str2json(xmlData);
			var divCuerpo = document.getElementsByClassName('cuerpo');
			for (i=0; i<divCuerpo.length; i++)
				divCuerpo[i].innerHTML = jsonData.notas.cuerpo;
		</script>
	<body>
</html>
 
Share this answer
 
v5
Comments
arun1904 31-Oct-15 4:11am    
Thanks George Jonsson, i cant change the xml data into CDATA,
Is there any other possibilties to use html tags.
I found a solution, but it won't work.

$("div").append("XML DATA");

The output came from the above code, shows the correct data into same page, we can not separate the individual data like json. is it possible to separate the xml content by using the above method.
George Jonsson 1-Nov-15 8:07am    
Why can't you wrap the HTML code in CDATA?

Not sure I understand what it is you want to do.
arun1904 3-Nov-15 1:58am    
Thanks @George Jonsson, as you said i have tried the above method which you said, while i wrap the html code in CDATA and converts it into json, the output contains - it replace the CDATA into json format.

Here is the plunker url, check this out
http://plnkr.co/edit/8I6mWw6nAnE1WbonZVbG?p=preview
George Jonsson 3-Nov-15 2:17am    
So it works now?
arun1904 3-Nov-15 5:27am    
no, it converts the CDATA into json, please check my plunker, style attributes are not working.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900