我希望将Json解析为Html,使用Angularjs,我正在使用Xml2json将Xml转换为Json

问题描述:

我使用angularjs http从服务器获取xml,我使用节点模块xml2json将其转换为json对象。我正确地返回了文档,但它看起来不正确,因为它在xml文档中有html标记。如果有人知道如何正确转换返回的json那将是很好的。

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.

var x2js = new X2JS();
var dom = x2js.xml_str2json(escapchr);




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



我仍​​在努力想出这个计算机编程的东西,我只有编写了几个月,所以请原谅我的错误代码和一些愚蠢的问题,但如果有人知道如何将json或xml解析为html,我将非常感激。


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.

您的根本问题是您从服务器获取的XML数据不是有效的XML文档。基本上你不能拥有角色<如果它不是XML节点,则在XML元素内部。



这种XML格式的中断导致任何标准的XML到JSON转换器失败。



您可以考虑以下几个选项:



1.将HTML代码包装在 CDATA [ ^ ]

这是它应该从服务器传送的方式

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



CDATA括号中的数据不会被解析,只会被视为元素值。

当您从服务器接收XML数据时,您可以自己插入CDATA包装。

只有在您需要考虑有限数量的HTML标记时,这才是可行的。否则您还必须为HTML标记编写解析器。

如果只有有限的数字,它也会起作用包含HTML数据的XML节点。例如,< cuerpo>如果它存在,将始终包含HTML。



2.将您自己的XML写入JSON转换器

您仍然会遇到加载问题的问题XML数据直接进入XmlDocument或XDocument,因此您可能不得不将XML数据视为纯文本。

然后你必须自己解析文本。

你例如,可以使用正则表达式来查找起始节点。


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_]*>



然后你可以插入斜杠作为第二个字符,并且你有结束节点。

剪切块,包括XML标签,并使用XElement,例如,阅读文本。

如果成功,你有一个有效的XML节点添加到XDocument。

如果失败,你可以检查块中是否有HTML代码。

如果是这样,你可以将数据包装在CDATA中。

如果你有一个有效的XML文档,你可以将它转换为JSON。



您还可以将每个节点直接转换为JSON一个。



这对新手来说并不是特别容易,所以希望你可以使用选项1.



或者其他人有更好的解决方案,更容易实现。



[更新]

工作示例


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

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