简体   繁体   English

用jQuery解析XML文本

[英]Parsing XML Text with jQuery

I'm working with a database that has X and Y points per group, it's being used to draw outlines of images. 我正在使用一个每组具有X和Y点的数据库,该数据库用于绘制图像轮廓。

Right now in my web side this code is what I use to get the points: 现在,在我的网络端,此代码是我用来说明要点的内容:

var Drawing = $(XML).find('DrawingXML');

alert($(Drawing[1]).text());

Result: 结果:

 <DrawingPoints>
   <Point><X>1</X><Y>2</Y></Point>
   <Point><X>2</X><Y>4</Y></Point>
   <Point><X>3</X><Y>5</Y></Point>
   <Point><X>2</X><Y>2</Y></Point>
   <Point><X>0</X><Y>4</Y></Point>
 </DrawingPoints>

Using the .replace() call only changes one item so it's usable for something like this: 使用.replace()调用仅更改一项,因此可用于如下所示:

.replace("</DrawingPoints>",""); 

but if I want to replace all 'Point' tags I'm out of luck. 但是如果我想替换所有的“ Point”标签,那我就不走运了。

My goal is to use the canvas feature to draw the points out so I want it to be parsed like this: 我的目标是使用画布功能绘制出点,因此我希望将其解析为:

ctx.beginPath();
ctx.moveTo(1,2);
ctx.lineTo(2,4);
ctx.lineTo(3,5);
ctx.lineTo(2,2);
ctx.lineTo(0,4);
ctx.stroke();

I'm not going to use this with IE browsers just Safari/Chrome, if that helps out. 如果有帮助,我不会在IE浏览器中仅使用Safari / Chrome。

Get all your X and Y values at once: 一次获取所有X和Y值:

var points = {};
points.X = Array();
points.Y = Array();
var ix = 0;

$(XML).find('DrawingXML DrawingPoints Point X').each(function()
{
    points.X[ix++] = $(this).text();
});
$(XML).find('DrawingXML DrawingPoints Point Y').each(function()
{
    points.Y[ix++] = $(this).text();
});

This might not be exact, I didn't test it and my Javascript is a bit rusty, but you get the idea. 这可能不准确,我没有测试它,但是我的Javascript有点生锈,但是您明白了。

In this case you'll probably save an awful lot of brainache by using a library instead of writing your own code. 在这种情况下,您可以通过使用库而不是编写自己的代码来节省很多麻烦。

I reckon d3 does what you need: 我认为d3可以满足您的需求:

Check out this question/answer. 查看此问题/答案。 It's not Prototype specific and should help you here. 它不是特定于原型的,应该在这里为您提供帮助。

How to parse XML string with Prototype? 如何使用原型解析XML字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM