提问者:小点点

用Javascript解析XML值


浏览器是IE8,我只想解析getValueCovid函数来检索acct_no。 另一个getValueFromStructure正在工作。

getValueCovid将完整的xml响应作为响应。

我有下面的XML,我已经有了一个javascript函数,从结构中获取元素。 我想要做的是编写一个独立的javascript函数,从'fields'级别检索ACCT_NO和值。 下面的代码

<Response>
    <Cl586>
        <Fields>
            <Field name="ACCT_NO">
                <Value>12345</Value>
            </Field>
            <Structure id="2002" index="1">
                <Field name="ACCT_STATUS">
                    <Value>TEST</Value>
                </Field>
            </Structure>
        </Fields>
    </Cl586>
</Response>

用于按索引获取结构的javascript工作:

getValueFromStructure : function (structure, name) {
    if (structure !== null && structure.hasOwnProperty('fields')) {
        for (var i=0; i < structure.fields.length; i++) {
            if (structure.fields[i].name === name) {
                return structure.fields[i].value;
            }
        }
    }
    return null;
},

我试图获取ACCT_NO,我想要修复该ACCT_NO

getValueCovid : function(response, name) {
    if (response !== null && response.hasOwnProperty('fields')) {
        for (var i=0; i < response.fields.length; i++) {
            if (response.fields[i].name === name) {
                return response.fields[i].value;
            }
        }
    }
    return null;
},

然后在seperate文件中,我要检索acct_no。 包括所以你有更多的想法:

$('#accountNumber').val(ClRestServices.getValueCovid(response, 'ACCT_NO'));

共1个答案

匿名用户

如果解析到标准DOM节点,可以使用querySelector等。

例如。

null

const text = `<Response>
    <Cl586>
        <Fields>
            <Field name="ACCT_NO">
                <Value>12345</Value>
            </Field>
            <Structure id="2002" index="1">
                <Field name="ACCT_STATUS">
                    <Value>TEST</Value>
                </Field>
            </Structure>
        </Fields>
    </Cl586>
</Response>`;


const parser = new DOMParser();
const xmlDoc = parser.parseFromString(text,"text/xml");

const value = xmlDoc.querySelector('Field[name=ACCT_NO] Value').textContent;


console.log(value);