如何将 XML 等文本解析为 javascript 对象

发布于 2024-12-15 08:23:30 字数 1545 浏览 4 评论 0原文

我创建了一个函数来执行此操作。

var text="adsf [name]Victor[/name] dummytext [name]Elliot[/name] asdf [name]Jake[/name] asdf [foo]bar[/foo]";

alert( readTags(text,'name') ); //Victor,Elliot,Jake
alert( readTags(text,'foo') ); //bar

但现在我想实现一个函数,它接收这样的字符串

[person]
    [name]jake[/name]
    [age]12[/age]
[/person]

并返回这样的对象

var object={};
object['person']={};
object['name']='jake';
object['age']='12';
return(object);

,但我不知道如何循环文本。如何处理开始和结束标签? 就像

[tag] [tag]value[/tag] [/tag]

我想使用 indexOf('[tag]')lastindexOf('[/tag]') 从左侧找到开始标签,从右侧找到结束标签,

但没有在这种情况下不起作用,

[tag]value[/tag] [tag]value[/tag]

这是之前的功能

function readTags(str,property){

    var beginTag='['+property+']';
    var endTag='[/'+property+']';

    var values=new Array(0);

    while(str.indexOf(beginTag)!=-1){
        values[values.length]=strBetween(str,beginTag,endTag);
        str=str.substring(str.indexOf(endTag)+endTag.length);
    }
    return(values);
}

function strBetween(string,strBegin,strEnd){    //StrBetween("abcdef","b","e")  //return "cd"

    var posBegin, posEnd;

    posBegin=string.indexOf(strBegin);
    string=string.substring(posBegin + strBegin.length);
    posEnd=string.indexOf(strEnd);
    string=string.substring(0,posEnd);

    if ((posBegin==-1)||(posEnd==-1)){
        return(null);
    }else{
        return(string);
    }
}

I created a function to do this.

var text="adsf [name]Victor[/name] dummytext [name]Elliot[/name] asdf [name]Jake[/name] asdf [foo]bar[/foo]";

alert( readTags(text,'name') ); //Victor,Elliot,Jake
alert( readTags(text,'foo') ); //bar

but now I like to implement a function that receive a string like this

[person]
    [name]jake[/name]
    [age]12[/age]
[/person]

and return a object like this

var object={};
object['person']={};
object['name']='jake';
object['age']='12';
return(object);

but I don't know how to loop through the text. How to deal with starting and ending tags?
like

[tag] [tag]value[/tag] [/tag]

I thought to find starting tag from left and ending tag from the right using indexOf('[tag]') and lastindexOf('[/tag]')

but doesn't work in this situation

[tag]value[/tag] [tag]value[/tag]

this is the previous function

function readTags(str,property){

    var beginTag='['+property+']';
    var endTag='[/'+property+']';

    var values=new Array(0);

    while(str.indexOf(beginTag)!=-1){
        values[values.length]=strBetween(str,beginTag,endTag);
        str=str.substring(str.indexOf(endTag)+endTag.length);
    }
    return(values);
}

function strBetween(string,strBegin,strEnd){    //StrBetween("abcdef","b","e")  //return "cd"

    var posBegin, posEnd;

    posBegin=string.indexOf(strBegin);
    string=string.substring(posBegin + strBegin.length);
    posEnd=string.indexOf(strEnd);
    string=string.substring(0,posEnd);

    if ((posBegin==-1)||(posEnd==-1)){
        return(null);
    }else{
        return(string);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

£烟消云散 2024-12-22 08:23:30

除非您有充分的理由使用JSON,否则不要这样做。 JSON 很好地处理了所有这些问题,并且可以很容易地从服务器到客户端,反之亦然。

但既然这看起来很有趣,我会尝试看看是否能找到答案。


由于您的结构类似于 XML,因此只需将括号替换为 <> 并像 XML 一样解析它:

text = text.replace('[', '<').replace(']', '>');

if (typeof DOMParser != "undefined") {
  var parser = new DOMParser();
  var xml = parser.parseFromString(text, 'text/xml');
} else {
  var xml = new ActiveXObject('Microsoft.XMLDOM');
  xml.async = 'false';
  xml.loadXML(text); 
}

现在 xml 包含一个 您可以解析的 DOMDocument

xml.getElementsByTagName('person').childnodes;

尝试这个可能有效的代码(未测试):

function createObject(element) {
  var object = {};

  if (element.childNodes.length > 0) {
    for (child in element.childnodes) {
      object[element.tagName] = createObject(child);
    }

    return object;
  } else {
    return element.nodeValue;
  }
}

Unless you have a good reason not to use JSON, don't do this. JSON handles all of those problems very well and can be floated around from server to client and vice versa quite easily.

But since this seems fun, I'll try and see if I can whip up an answer.


Since your structure resembles XML, just replace the brackets with < and > and parse it like XML:

text = text.replace('[', '<').replace(']', '>');

if (typeof DOMParser != "undefined") {
  var parser = new DOMParser();
  var xml = parser.parseFromString(text, 'text/xml');
} else {
  var xml = new ActiveXObject('Microsoft.XMLDOM');
  xml.async = 'false';
  xml.loadXML(text); 
}

Now xml holds a DOMDocument that you can parse:

xml.getElementsByTagName('person').childnodes;

Try this possibly-working code (didn't test):

function createObject(element) {
  var object = {};

  if (element.childNodes.length > 0) {
    for (child in element.childnodes) {
      object[element.tagName] = createObject(child);
    }

    return object;
  } else {
    return element.nodeValue;
  }
}
℉服软 2024-12-22 08:23:30

我认为如果没有第三方解析器,这会很有趣,所以我构建了一个简单的解析器:

function parse(code)
{
  var obj = {},
      cur = obj,
      stack = [];

  code.replace(/\[([^\]]+)\]|([^\[]*)/g, function (match, tagName, text) {
    if (tagName)
    {
      if (tagName.charAt(0) == "/")
      {
        /* end tag */
        cur = stack.pop();
      }
      else
      {
        /* start tag */
        stack.push(cur);
        cur = cur[tagName] = {};
      }
    }
    else
    {
      cur["#text"] = text;
    }
  });

  return obj;
}

var obj = parse(text);

I thought this would be interesting to do without a third-party parser, so I built me a simple one:

function parse(code)
{
  var obj = {},
      cur = obj,
      stack = [];

  code.replace(/\[([^\]]+)\]|([^\[]*)/g, function (match, tagName, text) {
    if (tagName)
    {
      if (tagName.charAt(0) == "/")
      {
        /* end tag */
        cur = stack.pop();
      }
      else
      {
        /* start tag */
        stack.push(cur);
        cur = cur[tagName] = {};
      }
    }
    else
    {
      cur["#text"] = text;
    }
  });

  return obj;
}

var obj = parse(text);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文