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'); 无济于事

还有其他想法吗?

4

6 回答 6

4

我同意 StructKeyExists 是您想要更改的内容:

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

对此:

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

您希望将要检查的最后一项以外的所有项目作为第一个参数。

于 2012-08-17T20:21:06.913 回答
0

This was my solution:

myEmpType = '';
    try{
    myEmpType = _XMLDoc.employee.name[1].xmlAttributes["EmpType"]; 
} catch (Any e) {
    myEmpType = 'no category';
}
于 2012-08-17T20:04:26.533 回答
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 这里这里有很好的信息。

于 2012-08-17T20:31:26.270 回答
0

我会使用 XPath 来解决这个问题:

XmlSearch(xmlObject, "//name[@EmpType]")

上面的表达式返回一个具有 EmpType 属性的节点数组,如果没有找到则返回一个空数组。所以你可以检查一个数组是否为空。如果您只需要一个布尔值,您可以像这样修改您的 xpath 字符串:

XmlSearch(xmlObject, "exists(//name[@EmpType])")

此表达式使用 xpath 函数exists(),如果找到具有该属性的任何节点,则返回 true,如果没有,则返回 false。整个表达式返回真或假,而不是像第一种情况那样的数组。返回类型的XmlSearch()变化取决于 xpath 表达式返回的内容。

于 2012-08-18T02:29:23.030 回答
0

尝试这个

<cfscript>
   employee.name[1].xmlAttributes["EmpType"]
</cfscript>
于 2012-08-17T19:55:56.427 回答
0

I use CFSCRIPT to parse XML.

When you test for the existence of a node, you should use structKeyExists(); This requires two paramenters, the scope and the variable. The scope cannot be in quotes. The variable MUST be in quotes.

structKeyExists(SCOPE, "Variable");

Here's s short bit that might help.

// 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);
于 2012-08-17T19:56:38.537 回答