如何在JavaScript中从一行XML获取属性

How to get attributes from a line of XML in JavaScript?

本文关键字:一行 XML 属性 获取 JavaScript      更新时间:2023-09-26

我把这行作为uml doc的一部分。

<children xmi:type="corstr:heighj" uml:name="private" x="255" y="188" width="221" height="51"/>
    我需要x,y的宽度和高度的值*

我试过这个函数

function getValues(mainBlock, valueLine)   {

console.log("searching for data in " + valueLine)
console.log("x? " + getValueFromLine(valueLine, "x='""));
console.log("y? " + getValueFromLine(valueLine, "y='""));
console.log("width? " + getValueFromLine(valueLine, "width='""));

function getValueFromLine(valueLine, searchFor)
{
    var position = valueLine.indexOf(searchFor);
    return valueLine.substr(position + searchFor.length, (valueLine.indexOf("'"", position + searchFor.length)) - position + searchFor.length);
}

但显然有些东西是错误的,所以我在控制台得到这个

x? 255" y="1<br>
index1.html:179 y? 188" width<br>
index1.html:180 width? 221" height="51"/

我不确定是否有解决方案,但我已经写了一个函数,可以帮助你。

我采用了分解字符串和分别解析属性的方法,并允许您根据需要使用元素-我已经编写了一个函数作为给定字符串的闭包。

它在SPACE上进行拆分,然后我解析分解并在EQUALS上进行拆分,然后解析整数,如果可能的话,最后创建一个包含解析值的对象。辅助函数包含在函数中,用于获取指定的值。

看一下小提琴,如果你看不懂代码,告诉我。

function parse_uml(valueLine) {
    var value_map = {};
    var breakdown = valueLine.split(" ");
    breakdown.shift();
    breakdown[breakdown.length - 1] = breakdown[breakdown.length - 1].substr(0, breakdown[breakdown.length - 1].length - 2);
    breakdown.map(function (i) {
        var attr = i.split("=");
        if (parseInt(attr[1].substr(1, attr[1].length - 2))) {
            value_map[attr[0]] = parseInt(attr[1].substr(1, attr[1].length - 2));
        } else {
            value_map[attr[0]] = attr[1].substr(1, attr[1].length - 2);
        }
    });
    return function (searchFor) {
        return value_map[searchFor];
    };
}

用法-

var parsed_uml = parse_uml('<children xmi:type="corstr:heighj" uml:name="private" x="255" y="188" width="221" height="51"/>', 'width');
console.log("Value of x - " + parsed_uml("x"));
console.log("Value of y - " + parsed_uml("y"));
console.log("Value of width - " + parsed_uml("width"));
http://jsfiddle.net/u6yxb4es/

嗨,我已经为您编写了一个XML解析器。这段代码将dom元素转换为对象。下面的代码可以帮助您从给定的XML标记中提取属性。

http://jsfiddle.net/wyqm16k0/

 function parsethis(line){
  var x = line.split(" "), dom = x.shift(), obj;
  dom = dom.replace("<","");
  x[x.length-1] = x[x.length-1].replace("/>","");
  x.forEach(function(element, index, array){
    var str = '"'+array[index];
    str = str.replace('=','":');
    array[index] = str;
  });
  obj = x.join("");
  obj = "{"+obj.replace(/""/g,'","')+"}";
  obj = JSON.parse(obj);
  obj.dom = dom;
  return obj;
}
var parsed = parsethis('<children xmi:type="corstr:heighj" uml:name="private" x="255" y="188" width="221" height="51"/>');
console.log("X = "+parsed.x,", Y = "+parsed.y, ", Width = "+parsed.width);

您可以使用DOMParser API将整个文档解析为xml文件,然后使用其getAttributeNS()方法像其他DOMElement一样获取您的元素。

由于我没有完整的文档,这里是一个概念证明,在未声明的xsi和uml的名称空间的属性已经从字符串中删除:

function cleanNS(input) {
  var str = input.split(' ');
  var cleaned = [];
  str.forEach(function(e) {
    if (e.split('=')[0].indexOf(':') === -1) {
      cleaned.push(e);
    }
  });
  return cleaned.join(' ');
}
var parser = new DOMParser();
var cleanDoc = cleanNS('<children xmi:type="corstr:heighj" uml:name="private" x="255" y="188" width="221" height="51"/>');
var element = parser.parseFromString(cleanDoc, 'application/xml').documentElement;
function log(str) {
  document.body.innerHTML = str;
}
log("x = " + element.getAttributeNS(null, 'x') + ", y = " + element.getAttributeNS(null, 'y') + ", width = " + element.getAttributeNS(null, 'width'));