使用CFSCRIPT获取XML属性

3

简单XML

<employee> 
    <name EmpType="Regular"> 
        <first>Almanzo</first> 
        <last>Wilder</last> 
    </name> 
</employee>

我正在尝试使用CFSCRIPT来测试属性"EmpType"是否存在。
尝试使用isDefined('_XMLDoc.employee.name[1].xmlAttributes.EmpType'),但无效。
尝试使用structkeyexists(_XMLDoc,'employee.name[1].xmlAttributes.EmpType'),但无效。
还有其他想法吗?
6个回答

4

我同意使用StructKeyExists,这是你想要改变的内容:

structkeyexists(_XMLDoc,'employee.name[1].xmlAttributes.EmpType')

到这里:
 structkeyexists(_XMLDoc.employee.name[1].xmlAttributes,'EmpType')

你需要将除了最后一个要检查的项之外的所有内容作为第一个参数。

0

试试这个

<cfscript>
   employee.name[1].xmlAttributes["EmpType"]
</cfscript>

我尝试了这个,但不幸的是,它没有找到属性的存在。 - Loony2nz

0

我使用CFSCRIPT来解析XML。

当您测试节点是否存在时,应使用structKeyExists()函数;它需要两个参数,作用域和变量。作用域不能加引号。变量必须加引号。

structKeyExists(SCOPE, "Variable");

这是一小段可能有所帮助的内容。

// BOOTH NUMBER
BoothInfo.BoothNumber = ResponseNodes[i].BoothNumber.XmlText;
writeOutput("<h3>BoothNumber - #BoothInfo.BoothNumber# </h3>");

// CATEGORIES
if (structKeyExists(ResponseNodes[i].ProductCategories, "Category")) {
    Categories = ResponseNodes[i].ProductCategories.Category;
    CatIDList = "";
    for (j = 1; j lte arrayLen(Categories); j++) {
        CatID = ResponseNodes[i].ProductCategories.Category[j].XmlAttributes.ID;
        CatIDList = listAppend(CatIDList, CatID);
    }
BoothInfo.CatID = CatIDList;
} else {
BoothInfo.CatID = "";
}
writeOutput(BoothInfo.CatID);

我并不建议您全部使用它,它只是一个有很多可能性的例子。 - Evik James

0
这是我的解决方案:
myEmpType = '';
    try{
    myEmpType = _XMLDoc.employee.name[1].xmlAttributes["EmpType"]; 
} catch (Any e) {
    myEmpType = 'no category';
}

那不是我建议的吗? - Hazem Salama

0

使用xmlsearch

为了测试它,我向您的XML添加了更多内容。

<employee> 
<name EmpType="Regular"> 
    <first>Almanzo</first> 
    <last>Wilder</last> 
</name>
<name> 
    <first>Luke</first> 
    <last>Skywalker</last> 
</name> 
</employee>

您会注意到,您的原始员工有EmpType,而第二个则没有。

这段代码可能有些冗长,但我只是想证明它可以工作。它循环遍历每个name节点,并检查它是否在其中有一个@EmpType。如果有,它就会卸载该XML节点。

names = xmlsearch(testXML,'employee/name');
for(n=1;n<=arraylen(names);n=n+1){
    thisname = names[n];
    hasemptype = xmlsearch(thisname,'@EmpType');
    if(arraylen(hasemptype)==1){
        writedump(thisname);    
    }
}

关于xmlsearch,这里很好的信息。


0
我会使用XPath来处理这个问题:
XmlSearch(xmlObject, "//name[@EmpType]")

上述表达式返回具有EmpType属性的节点数组,如果没有找到,则返回空数组。因此,您可以检查数组是否为空。如果您只需要布尔值,可以修改xpath字符串如下:
XmlSearch(xmlObject, "exists(//name[@EmpType])")

这个表达式使用了xpath函数exists(),如果找到任何带有该属性的节点,则返回true,否则返回false。整个表达式只返回true或false,而不像第一个情况中那样返回数组。 XmlSearch()的返回类型取决于xpath表达式的返回值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接